不能用日期替换 NA
Can't replace NA's with Date
出于某种原因我无法替换 NA,即使我使用 is.na 代码也是如此。我想用当前日期替换 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" ...
R 中的日期只是具有 Date
class 属性的 double
。一旦属性被剥离 - 它就变成了 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 中容纳多个 classes。来自 [<-.data.frame
When [ is used with a logical matrix, each value is coerced to the
type of the column into which it is to be placed.
调查 [<-.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)
出于某种原因我无法替换 NA,即使我使用 is.na 代码也是如此。我想用当前日期替换 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" ...
R 中的日期只是具有 Date
class 属性的 double
。一旦属性被剥离 - 它就变成了 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 中容纳多个 classes。来自 [<-.data.frame
When [ is used with a logical matrix, each value is coerced to the type of the column into which it is to be placed.
调查 [<-.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)