简体   繁体   中英

how to interate a list of columns names in purrr::map to create new columns in R

I want to perform an action against a list of columns in a dataframe using map() but I get an error which I can't understand, can anyone help?

I want it to recycle through the list of columns names in vec and to subtract against the values in column d, in dataframe df .

update: an answer was provided with across (which works) however i need to do this with map() not across()

library(tidyverse)

df <- tibble(a=seq.Date(from=ymd("2021-01-01"),to =ymd("2021-12-31"),by = "day"),
       b=seq.Date(from=ymd("2020-01-01"),to =ymd("2020-12-31"),by = "day"),
       c=seq.Date(from=ymd("2019-01-01"),to =ymd("2019-12-31"),by = "day"),
       d=seq.Date(from=ymd("2018-01-01"),to =ymd("2018-12-31"),by = "day")
)


vec <- c("a","b","c")

map(vec,~transmute(df,d-.x))

You may try the across

I updated the data to have dates from march instead of Jan, since feb has different # days and we will not get the dataframe generated


data


df <- tibble(a=seq.Date(from=ymd("2021-03-01"),to =ymd("2021-12-31"),by = "day"),
             b=seq.Date(from=ymd("2020-03-01"),to =ymd("2020-12-31"),by = "day"),
             c=seq.Date(from=ymd("2019-03-01"),to =ymd("2019-12-31"),by = "day"),
             d=seq.Date(from=ymd("2018-03-01"),to =ymd("2018-12-31"),by = "day")
)


vec <- c("a","b","c")

code

df %>% mutate(across(vec, ~ d-.x))

Created on 2023-01-28 with reprex v2.0.2

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