Reputation: 816
I have a list of nested data frames. I want to add a column of a sequential count to each nested dataframe.
This works in typical dataframe:
library(tidyverse)
mtcars %>% mutate(index = sequence(n()))
mpg cyl disp hp drat wt qsec vs am gear carb index
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 1
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 2
3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 3
4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 4
5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 5
But it does not work in a nested structure:
table <-
tribble(~id, ~data, 1, mtcars) %>%
mutate(data_index = map(data, ~mutate(.x, index = sequence(n()))))
table
# A tibble: 1 x 3
id data data_index
<dbl> <list> <list>
1 1 <data.frame [32 x 11]> <data.frame [32 x 12]>
head(table$data_index[[1]])
mpg cyl disp hp drat wt qsec vs am gear carb index
1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 1
2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 1
3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 1
4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 1
5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 1
6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 1
Any thoughts on how to overcome this?
Upvotes: 2
Views: 381
Reputation: 39154
I modified your code a little bit. The key is n()
returns the row number of the entire data frame, not mtcars
. So I used nrow(.x)
instead.
library(tidyverse)
dt <- tribble(~id, ~data, 1, mtcars)
dt2 <- dt %>%
mutate(data_index = map(data, ~mutate(.x, index = sequence(nrow(.x)))))
head(dt2$data_index[[1]])
# mpg cyl disp hp drat wt qsec vs am gear carb index
# 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 1
# 2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 2
# 3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 3
# 4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 4
# 5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 5
# 6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 6
Upvotes: 3