mutate for rows

tidyverse

#1

Is there a more laconic way to do the same without spread-mutate-gather lines?

library(tidyverse)

tibble(cola = letters[1:3], colb = 1:3) %>% 
    spread(cola, colb) %>% 
    mutate(d = c + 1) %>% 
    gather(cola, colb)

#> # A tibble: 4 x 2
#>   cola   colb
#>   <chr> <dbl>
#> 1 a         1
#> 2 b         2
#> 3 c         3
#> 4 d         4

Created on 2019-02-05 by the reprex package (v0.2.1)

I mean, to add one more row based on a previous one. Let's call it "mutate for rows".
When I say "laconic", I mean in no more than 3 lines and still staying in the pipeline, without intermediate assignments.


#2

You can use add_row():

In your example you would first have to identify the last row for the value you would like to increment.


#3

I haven't known this function, thank you. But I don't see how it can create a row based on a previous one


#4

This is an ugly method:

library(tidyverse)

x <- tibble(cola = letters[1:3], colb = 1:3)
lastval <- x %>% filter(row_number() == n()) %>% pull(colb)
x %>% add_row(cola = "d", colb = lastval + 1)

I hope somebody has a more elegant solution.


#5

Building on the add_row approach, maybe something like this?

library(tidyverse)

tibble(cola = letters[1:3], colb = 1:3) %>%
  add_row(cola = "d", colb = last(.$colb) + 1)
#> # A tibble: 4 x 2
#>   cola   colb
#>   <chr> <dbl>
#> 1 a         1
#> 2 b         2
#> 3 c         3
#> 4 d         4

Created on 2019-02-10 by the reprex package (v0.2.1)


#6

this can't be last command because it covers only one specific case. What if d = b * 2?