将向量中的空值替换为0

时间:2019-02-19 13:02:55

标签: r replace

我正在尝试在变量中查找空值,并在满足条件的情况下将其替换为0。但是此代码似乎不起作用。

 if(Begin_date <= Date_new & sapply(Var4,is.null)){Var4=0}

我应该对Var4使用for循环,然后替换其值吗?请注意Var4具有86500值,类型为“ DBL”。

       ID  Year Month Begin_date                             Var4 Date_new  
     <dbl> <dbl> <dbl> <dttm>                               <dbl> <date>    
 1      7  2011     1 2008-01-01 00:00:00                        2010-01-01
 2      7  2011     2 2008-01-01 00:00:00                      0 2010-02-01
 3      7  2011     3 2008-01-01 00:00:00                      0 2010-03-01
 4      7  2011     4 2008-01-01 00:00:00                      0 2010-04-01
 5      7  2011     5 2008-01-01 00:00:00                      0 2010-05-01
 6      7  2011     6 2008-01-01 00:00:00                      0 2010-06-01
 7      7  2011     7 2008-01-01 00:00:00                      0 2010-07-01
 8      7  2011     8 2008-01-01 00:00:00                      0 2010-08-01
 9      7  2011     9 2008-01-01 00:00:00                        2010-09-01
10      7  2011    10 2008-01-01 00:00:00                      0 2010-10-01

我也尝试过:

if(Begin_date <= Date_new & sapply(Var4,is.null)){
for(i in 1:nrow(Basedata)){Var4[i]<-0}}

但是我收到此错误:

the condition has length > 1 and only the first element will be used

1 个答案:

答案 0 :(得分:0)

在以上评论的帮助下,该解决方案对我有效:

 Data$Var4Copy<-ifelse(Begin_date <= Date_new & is.na(Data$Var4),Data$Var4Copy[is.na(Data$Var4)] <- 0, Data$Var4Copy<- Data$Var4)
相关问题