Hi community,
I'd like to modify the first value (numeric) of a nested list in a tibble by adding another numeric variable. I need to do this by position as the list elements have different names in different rows.
My investigations so far have led me to believe list_modify
is the function that will get me there, but I can't figure out how to modify by list position rather than list name. The list elements have different names and lengths, which is why I'd like to modify by position.
Looking at the vignettes on the tidyverse site and in R documentation, the examples seem to me to only call by name, not by position.
Here's an explanatory tibble and examples of various broken, confused, gibberish code that I tried that failed.
In this example, I'd like to create a new variable par_adj
where the first element of each par
list is tweaked by adding the adj
variable.
# Initialise a test tibble.
(test_tibble <- tibble(
dist = c("norm", "exp"),
par = list(
list(mean = 1, sd = 1),
list(rate = 3)
),
adj = rep(2, 2)
))
# I wish to add the parameter adjustment adj to the first element of the par list. As the par list contains values with different names, I'd like to add adj to the first element of par by the first position.
# This doesn't work, and I'm not really sure how to use the ..n call or what it means, but I saw something about it in .
# test_tibble %>%
# mutate(par_adj = list_modify(par, ..1 = list(map_dbl(par, 1) + adj)))
# Perhaps I need to map first. Not sure how tell list_modify to change the first value.
# test_tibble %>%
# mutate(par_adj = map(
# par,
# list_modify,
# 1,
# ~1 + adj
# ))
# Nope, this doesn't work either.
# test_tibble %>%
# mutate(par_adj = map(
# par,
# list_modify,
# 1,
# list(map_dbl(par, 1) + adj)
# ))
Cheers