Reputation: 757
I want to convert numeric data in columns 2:4 to dates. I can do this column by column but can't do it all it all in one go. I figure it has something to do with the names column being in there, but I try to tell R just to use the columns I want. What am I doing wrong? Thanks in advance!
names<-c("tom", "dick", "harry", "mary", "susie")
date_1<-c(15127, 15034, 15034, 15141, 15013)
date_2<-c(15155, 15062, 15064, NA, 15041)
date_3<-c(15185, 15091, 15092, NA, 15069)
df<-data.frame(names, date_1, date_2, date_3)
df
as.Date(df$date_1, origin="1970-01-01")
[1] "2011-06-02" "2011-03-01" "2011-03-01" "2011-06-16" "2011-02-08"
as.Date(df[,2:4], origin="1970-01-01")
Error in as.Date.default(df[, 2:4], origin = "1970-01-01") :
do not know how to convert 'df[, 2:4]' to class “Date”
Upvotes: 0
Views: 2421
Reputation: 173517
Data frames are lists. Use lapply
:
df[,-1] <- lapply(df[,-1],as.Date,origin = "1970-01-01")
> df
names date_1 date_2 date_3
1 tom 2011-06-02 2011-06-30 2011-07-30
2 dick 2011-03-01 2011-03-29 2011-04-27
3 harry 2011-03-01 2011-03-31 2011-04-28
4 mary 2011-06-16 <NA> <NA>
5 susie 2011-02-08 2011-03-08 2011-04-05
Upvotes: 2