In this example, I have two lists
tiers <- list("tier 1", "tier 2", "tier 3")
main <- list(data.frame(a = c("this", "that")),
data.frame(a = c("the other", "that too")),
data.frame(a = c("once more", "kilgore trout")))
and I'd like to mutate()
each list element (i.e., data.frame()
) in main
by adding the value in tiers
from the corresponding element. I thought mapply()
would do it:
library(dplyr)
mapply(function(x, y) y %>% mutate(tier = x), tiers, main)
but I get an unexpected result
> mapply(function(x, y) y %>% mutate(tier = x), tiers, main)
[,1] [,2] [,3]
a factor,2 factor,2 factor,2
tier Character,2 Character,2 Character
while what I expected was
[[1]]
a tier
1 this tier 1
2 that tier 1
[[2]]
a tier
1 the other tier 2
2 that too tier 2
[[3]]
a tier
1 once more tier 3
2 kilgore trout tier 3
Am I using mapply()
correctly? If not, is there something I should be using to get the result I'm expecting? I should note that actual data may have up to n
list elements; I can't hard-code any values in terms of 1:n
.