如何将一列中的NA
替换为另一列中的值(当所有值都是日期时)?我可以用数字来做,但是当我尝试
mydata$enddate <- ifelse(!is.na(mydata$End.date.html),
mydata$End.date1,
mydata$End.date2)
它将所有日期更改为不相关的数字。我确信有一种方法可以替换丢失的日期。
答案 0 :(得分:3)
一种方法是存储列中的哪些值为NA,然后使用该向量查询第二列并将这些值分配回第一列,如下所示:
invalid.dates <- is.na(mydata$datecol1)
if(any(invalid.dates)) {
mydata$datecol1[invalid.dates] <- mydata$datecol2[invalid.dates]
}
答案 1 :(得分:1)
直接从ifelse
文档(?ifelse
)示例:
> ## ifelse() strips attributes
> ## This is important when working with Dates and factors
> x <- seq(as.Date("2000-02-29"), as.Date("2004-10-04"), by = "1 month")
> head(x)
[1] "2000-02-29" "2000-03-29" "2000-04-29" "2000-05-29" "2000-06-29" "2000-07-29"
> ## has many "yyyy-mm-29", but a few "yyyy-03-01" in the non-leap years
> y <- ifelse(as.POSIXlt(x)$mday == 29, x, NA)
> head(y) # not what you expected ... ==> need restore the class attribute:
[1] 11016 11045 11076 11106 11137 11167
> class(y) <- class(x)
> head(y)
[1] "2000-02-29" "2000-03-29" "2000-04-29" "2000-05-29" "2000-06-29" "2000-07-29"
答案 2 :(得分:-1)
我会完全放弃ifelse
:
mydata$enddate<-mydata$End.date1
mydata$enddate[is.na(mydata$End.date1)]<-mydata$End.Date2[is.na(mydata$End.date1)]