我想将第2列到第4列中的数值数据转换为日期。我可以逐列完成此操作,但不能一次完成所有操作。我认为它与那里的名称列有关,但我试图告诉R只是使用我想要的列。我究竟做错了什么?提前谢谢!
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”
答案 0 :(得分:1)
数据框是列表。使用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