1

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

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”
4

2 回答 2

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"]是 class data.frame,所以x参数使用as.Date.default是因为没有as.Date.data.frame方法。触发错误是因为x针对FALSE所有if语句并继续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.character或传递给as.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"
于 2014-11-21T20:53:54.677 回答
3

如果要对单个数据框中的多个列执行此操作,请使用该lapply函数。就像是:

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

mydf[colNames] <- lapply( mydf[colNames], as.Date, "%m/%d/%Y" )
于 2014-11-21T21:13:08.177 回答