下标作业中不允许日期错误 NA

Dates error NAs are not allowed in subscripted assignments

考虑以下数据集。它涉及失业咒语的最后日期,但目前它可以简单地看作是在满足某些特征时更改结束日期。

df<-data.frame( c("R007", "R008", "R009", "R010"), 
                c(20130101, 20130201 ,20130301, 20130610),
                c(20141231, 20141031, 20141231,20141231),
                c(NA,             NA, 20151231, 20151232),
                c(NA,       20161001, 20160601, 20161010),
                c(NA, 20170101, 2171201, 20171101)) 
               

colnames(df)<-c("id", "beginui", "endui.year1", "endui.year2", "endui.year3", "endui.year4")



df$beginui<-as.character(df$beginui)
df$beginui<-as.Date(df$beginui, "%Y%m%d")

df$endui.year1<-as.character(df$endui.year1)
df$endui.year1<-as.Date(df$endui.year1, "%Y%m%d")

df$endui.year2<-as.character(df$endui.year2)
df$endui.year2<-as.Date(df$endui.year2, "%Y%m%d")

df$endui.year3<-as.character(df$endui.year3)
df$endui.year3<-as.Date(df$endui.year3, "%Y%m%d")

df$endui.year4<-as.character(df$endui.year4)
df$endui.year4<-as.Date(df$endui.year4, "%Y%m%d")

#create an enddate variable
df$enddate<-df$endui.year1

#replace the enddate when certain conditions are met

#this one runs
#purpose of this line: change the enddate of the date in year 1 equals 2014/12/31 by the date in #year 2.
df$enddate[df$endui.year1==as.Date("2014-12-31") & !is.na(df$endui.year2)]<-df$endui.year2[!is.na(df$endui.year2)]

#this one does not run. 
#Error in NextMethod(.Generic): NAs are not allowed in subscripted assignments

#purpose if this line: change the enddate to the variable in year 3 if the final data equals 2015-12-31
df$enddate[df$endui.year2==as.Date("2015-12-31") & !is.na(df$endui.year3)]<-df$endui.year3[!is.na(df$endui.year3)]

正如代码行中已经指出的那样,第二个条件不 运行。同时我不知道为什么。我在本网站的此处 (NAs are not allowed in subscripted assignments) 检查以确保我没有 select NA。然而,表面上看 我在第二行漏掉了一些东西,但我没有看到什么。

表达式:

df$enddate[df$endui.year2 == as.Date("2015-12-31") & !is.na(df$endui.year3)]

产生 NA 个值:

#> [1] NA           "2015-12-31" NA  

如果您将逻辑条件包装在 which

中,这些就会消失
df$enddate[which(df$endui.year2 == as.Date("2015-12-31") & !is.na(df$endui.year3))]
#> [1] "2014-12-31"

但是对于您希望移动的日期,您也需要具有相同的条件(您需要 select df$endui.year2 == as.Date("2015-12-31") 行中的 endui.year2 值)将其移动到正确的位置。也许最简单的方法是先设置条件

condition1 <- which(df$endui.year1 == as.Date("2014-12-31") & !is.na(df$endui.year2))
df$enddate[condition1] <- df$endui.year2[condition1]

condition2 <- which(df$endui.year2 ==a s.Date("2015-12-31") & !is.na(df$endui.year3))
df$enddate[condition2] <- df$endui.year3[condition2]

这导致:

df
#>     id    beginui endui.year1 endui.year2 endui.year3 endui.year4    enddate
#> 1 R007 2013-01-01  2014-12-31        <NA>        <NA>        <NA> 2014-12-31
#> 2 R008 2013-02-01  2014-10-31        <NA>  2016-10-01  2017-01-01 2014-10-31
#> 3 R009 2013-03-01  2014-12-31  2015-12-31  2016-06-01        <NA> 2016-06-01
#> 4 R010 2013-06-10  2014-12-31        <NA>  2016-10-10  2017-11-01 2014-12-31