将字符串data.frame转换为Date

时间:2014-11-21 20:44:59

标签: r string dataframe as.date

我想知道为什么会出现这种错误。我想使用括号转换它,因为我在循环中进行顺序转换。因为我只是希望能够做到这一点,并了解正在发生的事情。

head(clean.deposit.rates)
       Date
1 1/31/1983
2 2/28/1983
3 3/31/1983
4 4/30/1983
5 5/31/1983
6 6/30/1983

class(clean.deposit.rates)
[1] "data.frame"

class(as.Date(clean.deposit.rates[[1]], "%m/%d/%Y"))
[1] "Date"



    class(as.Date(clean.deposit.rates$Date, "%m/%d/%Y"))
[1] "Date"



 as.Date(clean.deposit.rates["Date"], "%m/%d/%Y")
    Error in as.Date.default(clean.deposit.rates["Date"], "%m/%d/%Y") : 
      do not know how to convert 'clean.deposit.rates["Date"]' to class “Date”

2 个答案:

答案 0 :(得分:3)

您需要使用两个[括号。使用一个,列保持为数据框。有了两个,它就变成了一个原子向量,可以正确地传递给正确的as.Date方法

as.Date(df["Date"], "%m/%d/%Y")
# Error in as.Date.default(df["Date"], "%m/%d/%Y") : 
#   do not know how to convert 'df["Date"]' to class “Date”

由于df["Date"]是类data.framex参数使用as.Date.default,因为没有as.Date.data.frame方法。由于所有x语句的FALSEif,因此会触发错误,并继续as.Date.default到该行

stop(gettextf("do not know how to convert '%s' to class %s", 
     deparse(substitute(x)), dQuote("Date")), domain = NA) 

使用df[["Date"]],该列成为一个向量,并根据向量的类传递给as.Date.characteras.Date.factor,并返回所需的结果。

as.Date(df[["Date"]], "%m/%d/%Y")
# [1] "1983-01-31" "1983-02-28" "1983-03-31" "1983-04-30" "1983-05-31"
# [6] "1983-06-30"

答案 1 :(得分:3)

如果要对单个数据框中的多个列执行此操作,请使用lapply功能。类似的东西:

colNames <- c('StartDate','EndDate')

mydf[colNames] <- lapply( mydf[colNames], as.Date, "%m/%d/%Y" )