根据列值用 0 填充 NA 值

Fill NA values with 0 based on columns values

我有以下数据:

df <- data.frame( V1 = c("A", "B","C","D", "E", "F"), V2 = c(2011,2012,2013,2014, 2015, 2016),V3= c(1,3, NA, NA, NA, NA))    

V3 上用 0 填充 NA 值很容易完成,正如此处已经讨论过的:blank elements in Excel: how to fill them as 0 in R。我的疑问是如何根据 V2 中的值将此操作限制为某些行。例如,在 V3 中仅在值范围从 20132015V2 行上用 O 填充 NA。期望的输出:

df <- data.frame( V1 = c("A", "B","C","D", "E", "F"), V2 = c(2011,2012,2013,2014, 2015, 2016),V3= c(1,3, 0, 0, 0, NA))    

试试这个:

for (i in 1:nrow(df))
  if (df$V2[i] %in% c("2013","2014","2015"))
    df$V3[i]<-0

同时使用 sqldf 包:

df<-sqldf(c("update df set V3=0 where V2 in ('2013','2014','2015')", 
"select * from df "))

这是一种可能性:

df$V3[with(df, is.na(V3) & V2 >= 2013 & V2 <= 2015)] <- 0

感谢@mtoto 指出应该添加条件 is.na()

指定要用零替换 NA 的列号。

df[ df$V2>=2013 & df$V2 <= 2015 & is.na(df$V3),3]=0