Rory Nolan
Rory Nolan

Reputation: 1042

Error when using dplyr::mutate with mapply

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?

Upvotes: 3

Views: 637

Answers (2)

eipi10
eipi10

Reputation: 93871

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))

Upvotes: 1

Hong Ooi
Hong Ooi

Reputation: 57696

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

Upvotes: 2

Related Questions