Error when using dplyr::mutate with mapply

633 views Asked by At

I want to use mutate on each of two data frames in a list, adding a column z = 3 to the first and z = 4 to the second (and returning a list of two data frames).

dfs <- list(data.frame(x = 1), data.frame(y = 2))
mapply(dplyr::mutate, dfs, z = 3:4, SIMPLIFY = FALSE)
#> Error in lazyeval::lazy_dots(...): Promise has already been forced

What's going wrong for me, and how should I go about doing what I want to do?

2

There are 2 answers

0
eipi10 On

You could also do this with map2 from the purrr package if you want to stay in the tidyverse:

library(purrr)
library(dplyr)

map2(dfs, 3:4, ~ .x %>% mutate(z=.y))
[[1]]
  x z
1 1 3

[[2]]
  y z
1 2 4

You can also pipe the list into map2:

dfs %>% map2(3:4, ~ .x %>% mutate(z=.y))
3
Hong Ooi On

Using an anonymous function works:

mapply(function(df, z) mutate_(df, z=z), dfs, 3:4, SIMPLIFY=FALSE)
#[[1]]
#  x z
#1 1 3
#
#[[2]]
#  y z
#1 2 4