当所有值都是日期时,将一列中的NAs替换为另一列中的值

时间:2018-03-19 00:35:34

标签: r date replace

如何将一列中的NA替换为另一列中的值(当所有值都是日期时)?我可以用数字来做,但是当我尝试

时为日期值
mydata$enddate <- ifelse(!is.na(mydata$End.date.html), 
                         mydata$End.date1, 
                         mydata$End.date2)

它将所有日期更改为不相关的数字。我确信有一种方法可以替换丢失的日期。

3 个答案:

答案 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)]