为什么我的因子列值不会更改为日期值?

时间:2014-10-21 02:44:14

标签: date

我知道这是基本的,但即使在阅读其他帖子之后,我似乎无法弄明白。

在数据集中,我想将整个列转换为日期。当前的类是因子。

该字段中的值类似于12/25/2012

这是我尝试过的。

 C$DateofDeath=as.Date(C$DateofDeath,'%m/%d/%Y')
Error in as.Date.default(C$DateofDeath, "%m/%d/%Y") : 
  do not know how to convert 'C$DateofDeath' to class “Date”

 C$DateofDeath=as.Date(C$DateofDeath,"%m/%d/%Y")
Error in as.Date.default(C$DateofDeath, "%m/%d/%Y") : 
  do not know how to convert 'C$DateofDeath' to class “Date” 

Claims$DateofDeath=strptime(as.character(Claims$DateofDeath),format= '%m/%d/%Y')
Error in `$<-.data.frame`(`*tmp*`, "DateofDeath", value = list(sec = numeric(0),  : 
  replacement has 0 rows, data has 71616

Claims$DateofDeath=strptime(as.character(Claims$DateofDeath),format= "%m/%d/%Y")
Error in `$<-.data.frame`(`*tmp*`, "DateofDeath", value = list(sec = numeric(0),  : 
  replacement has 0 rows, data has 71616

2 个答案:

答案 0 :(得分:0)

使用as.POSIXct

C $ DateOfDeath&lt; -as.POSIXct(as.character(C $ DateOfDeath),format =&#34;%d /%m /%Y&#34;)

答案 1 :(得分:0)

这里有很多R专家,但您必须指定R作为标记之一才能让他们注意到您的问题。

看起来你已经尝试了很多组合但不是正确的组合。

> C <- data.frame(DateofDeath="12/25/2012",other=TRUE)
> as.Date(as.character(C$DateofDeath),format="%m/%d/%Y")
[1] "2012-12-25"

请注意as.Date()采用字符输入,而不是因素。所以你需要转换为character,然后转换为Date。

您的strptime()版本对我来说似乎不错,只是您的来电是指数据框Claims而不是C。实际上strptime()应该为您将因子转换为字符,因此您不需要as.character()部分。