根据列值

时间:2016-02-19 11:21:23

标签: r na

我有以下数据:

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))    

NA上使用0填写V3值可以轻松完成,如此处所述:blank elements in Excel: how to fill them as 0 in R。我怀疑的是如何根据V2中的值将此操作限制为某些行。例如,仅NAO中填充V3 20132015上的值V2df <- 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)) 。期望的输出:

getData()

3 个答案:

答案 0 :(得分:2)

这是一种可能性:

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

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

答案 1 :(得分:0)

试试这个:

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 "))

答案 2 :(得分:0)

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

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