gray
February 5, 2019, 12:06pm
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.
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
gray
February 5, 2019, 12:28pm
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
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.
Carl
February 10, 2019, 7:21pm
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)
1 Like
gray
February 11, 2019, 10:04am
6
this can't be last
command because it covers only one specific case. What if d = b * 2
?
system
Closed
March 4, 2019, 10:15am
7
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.