简体   繁体   中英

How to use map2 to add column to list of dataframes

I'm trying to use map2 to add a column to each dataframe within a list

Here is my attempt:

weather_data <- weather_data %>%
                map2(x, y = c("Place1", "Place2", "Place3", "Place4"), ~ x[["Area"]] = y)

The idea of this is to add a column entitled "Area" to each dataframe. So the first dataframe in the list would have a column "Area" with a value of "Place1" and so forth...

Many thanks

This can be achieved like so:

BTW: First. The arguments to purrr::map2 are .x and .y .

list(mtcars, iris, mtcars, iris) %>%
  purrr::map2(.y = c("Place1", "Place2", "Place3", "Place4"), function(x, y) { x[["Area"]] <- y; x })

We can also make use of the ~ notation in map2 along with mutate from dplyr

library(dplyr)
library(purrr)
list(mtcars, iris, mtcars, iris) %>%
    map2(c("Place1", "Place2", "Place3", "Place4"), ~ 
               .x %>%
                   mutate(Area = .y))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM