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

Time:01-29

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

CodePudding user response:

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

  • Related