简体   繁体   中英

How can I apply a function to a list of dataframes in R?

I am trying to bind many dataframes. They all have the same number of columns and same column names. However, bind_rows won't work because some dataframes have a specific column stored as date and some as character. How can I apply a function that converts date to character or viceversa in all dataframes? Better yet if I convert all date columns in all dataframes. Here is some dummy code of what I am trying to do:

    library(tidyverse)

employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))

startdate.2<-c('2010-11-1','2008-3-25','2007-3-14')


df1<-data.frame(employee,salary, startdate)
df2<-data.frame(employee,salary, startdate.2) %>% rename(startdate=startdate.2)

df3<-bind_rows(df1,df2)

Error: Can't combine ..1$startdate and ..2$startdate .

Thanks for any help!

Here's how you can convert all date columns to character columns using purrr

list(df1, df2) %>% 
  map(~mutate(.x, across(where(lubridate::is.Date), as.character))) %>% 
  bind_rows()

or if you wanted to convert all columns with the "date" in their name to Date values you could do

list(df1, df2) %>% 
  map(~mutate(.x, across(contains("date"), as.Date))) %>% 
  bind_rows()

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