无法用日期替换NA

时间:2016-04-06 14:48:27

标签: r dataframe na

即使我使用is.na代码,我也无法替换NA& s。我想用当前日期替换NA。有任何想法吗?

以下是我的数据框:

df 

      Name     Parent        Date
1     A        no parent     OLD
2     B        no parent     NA
3     C        no parent     OLD
4     D        no parent     OLD
5     E        no parent     OLD

当我尝试使用此代码时,它无法正常工作:

today <- Sys.Date()
df[["Date"]][is.na(df[["Date"]])] <- today

str(df)
'data.frame':   2505 obs. of  3 variables:
 $ Name  : chr  " A" " B"  "C" "D" ...
 $ Parent: chr  "no parent" "no parent" "no parent" "no parent" ...
 $ Date  : chr  "OLD" NA "OLD" "OLD" ...

1 个答案:

答案 0 :(得分:2)

R中的日期只是double,具有Date类属性。一旦属性被剥离 - 它就变成了double。见

attributes(today)
# $class
# [1] "Date"

unclass(today)
# [1] 16897

storage.mode(today) ## data.table::as.IDate uses an integer storage mode
# [1] "double"

单个列不能在R中保存多个类。来自[<-.data.frame

  

当[与逻辑矩阵一起使用时,每个值都被强制转换为   要放置的列的类型。

调查[<-.data.frame文档我不确定如何转换为character,可能

as.character(`attributes<-`(today, NULL))
# [1] "16897"

或者

as.character(unclass(today))
# [1] "16897"

在寻找时

as.character(today)
## [1] "2016-04-06"

总而言之,这应该做

df[is.na(df$Date), "Date"] <- as.character(today)