mutate for rows

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.

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.

2 Likes

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

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.

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)

1 Like

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

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.