I have to be missing something obvious here... I'm trying to add a column to each element of a list-column of data, where the new column name corresponds to the name of an element in another column.
Example data
library(dplyr, warn.conflicts = FALSE)
library(purrr)
df1 <- tibble(
new_cols = c("y", "z"),
data = list(
tibble(a = 1),
tibble(b = 1)
)
)
df1
# A tibble: 2 x 2
new_cols data
<chr> <list>
1 y <tibble [1 x 1]>
2 z <tibble [1 x 1]>
df1$data[[1]]
# A tibble: 1 x 1
a
<dbl>
1 1
Calling an anonymous function
So, I would like to add a column called "y" to the first tibble in the list, and a column called "z" to the second tibble in the list. I would like to accomplish this by calling an anonymous function, but the following results in an error:
df1 %>%
mutate(data2 = map2(
.x = data,
.y = new_col,
.f = function(x, y) mutate(x, {{ y }} := 2)
))
#> Error in (function (x) : object 'y' not found
map
seems to be looking for an object "literally" called "y", which of course is not correct.
Using a function saved to an object
However, if I create a function and assign it to an object then I can map it to the data without any issues:
my_mutate <- function(.data, .colname) {
mutate(.data, {{ .colname }} := 2)
}
df2 <-
df1 %>%
mutate(data2 = map2(
.x = data,
.y = new_cols,
.f = my_mutate
))
pull(df2, data2)
[[1]]
# A tibble: 1 x 2
a y
<dbl> <dbl>
1 1 2
[[2]]
# A tibble: 1 x 2
b z
<dbl> <dbl>
1 1 2
Can anyone explain what I'm missing here?
Thanks!