I am working with list columns. One column is the the data of interest, and another is a list of row indices for the the data. I would like to dynamically add and title new columns to the List column. Each new column should be a subset of the data sliced by the indices stored in the other column. I am able to create one new list column, but if I try and index a mapping variable it does not work. The example below reproduces what I have done so far.
library(tidyverse)
# This sample mimics the structure of my data
LC <- mtcars %>%
as_tibble() %>%
group_by(gear) %>%
nest() %>%
rowwise() %>%
mutate(inds = list(as.integer(ceiling(runif(n = gear))))) %>%
group_by(gear) %>%
print()
And the following map function works if I want to mutate 1 new column
LC.slice <- LC %>%
mutate(slices = map2(.x = data,
.y = inds,
~ .x %>%
slice((.y[[1]] - 1): (.y[[1]] + 1)))) %>%
print()
But my goal is to dynamically create and name many columns. So I tried a function like this:
LC.slicer <- function(df, var1, var2){
for (i in 1:3){
df <- df %>%
mutate("slice_{i}" := map2(.x = {{ var1 }},
.y = {{ var2 }},
~ .x %>%
slice((.y[[i]] - 1): (.y[[i]] + 1))))
}
}
# and then call the function
LC.sliced <- LC.slicer(LC, data, inds) %>% print()
but this function returns NULL.
How can I successfully index to make a function?
Just return the object after the for loop
LC.slicer <- function(df, var1, var2){
for (i in 1:3){
df <- df %>%
mutate("slice_{i}" := map2(.x = {{ var1 }},
.y = {{ var2 }},
~ .x %>%
slice((.y[[i]] - 1): (.y[[i]] + 1))))
}
df
}
-testing
> LC.slicer(LC, data, inds)
# A tibble: 3 × 6
# Groups: gear [3]
gear data inds slice_1 slice_2 slice_3
<dbl> <list> <list> <list> <list> <list>
1 4 <tibble [12 × 10]> <int [4]> <tibble [2 × 10]> <tibble [2 × 10]> <tibble [2 × 10]>
2 3 <tibble [15 × 10]> <int [3]> <tibble [2 × 10]> <tibble [2 × 10]> <tibble [2 × 10]>
3 5 <tibble [5 × 10]> <int [5]> <tibble [2 × 10]> <tibble [2 × 10]> <tibble [2 × 10]>