Reputation: 2085
I got the following datasets:
dflist <- list(mtcars, mtcars)
dflist[[1]] %>%
mutate(cyl2 = cyl * 2)
This works!
dflist %>%
map(.x, ~.x$cyl2 = .x$cyl * 2)
Error: unexpected '=' in:
"dflist %>%
map(.x, ~x$cyl2 ="
This results in an error. I tried other options, but the function does not except the =
sign. What is wrong there?
Upvotes: 1
Views: 79
Reputation: 886938
We can use transform
without anonymous function call in base R
lapply(dflist, transform, cyl2 = cyl *2)
Upvotes: 0
Reputation: 39858
You can also try:
modify(dflist, ~ update_list(., cyl2 = ~ cyl * 2))
[[1]]
mpg cyl disp hp drat wt qsec vs am gear carb cyl2
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 12
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 12
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 8
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 12
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 16
[[2]]
mpg cyl disp hp drat wt qsec vs am gear carb cyl2
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 12
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 12
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 8
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 12
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 16
Upvotes: 2
Reputation: 388817
Try :
library(dplyr)
library(purrr)
dflist %>% map(~.x %>% mutate(cyl2 = cyl * 2))
#[[1]]
# mpg cyl disp hp drat wt qsec vs am gear carb cyl2
#1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 12
#2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 12
#3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 8
#4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 12
#5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 16
#....
#[[2]]
# mpg cyl disp hp drat wt qsec vs am gear carb cyl2
#1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 12
#2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 12
#3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 8
#4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 12
#5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 16
#...
Or keeping it in base R:
lapply(dflist, function(x) transform(x, cyl2 = cyl * 2))
Upvotes: 2