Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

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!

question from:https://stackoverflow.com/questions/65852241/how-can-i-apply-a-function-to-a-list-of-dataframes-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...