我有一個包含大量數值變量的數據集和一個字符變量,表示是否抑制了該觀察值的低值。在值不被抑制的觀察值中,我想替換NAs 0(僅針對特定變量),而我無法弄清楚。這是我的數據:根據條件替換NA
suppressed var1 var2
none 2 6
none NA 6
none 3 7
none NA NA
full 2 6
full 3 6
none 3 NA
partial NA 6
none 2 7
none NA NA
如果Suppressed = none,我想要做的就是將Var 1中的NA更改爲0。我試圖
df$Var1<-if (df$suppressed=='none'&is.na(df$Var1)) 0
else df$Var1
,並得到
Error in if (df$suppressed == "none" & is.na(df$Var1)) 0 else df$Var1 :
argument is of length zero
是不是有什麼毛病我如果else語句,或有另一種方式做到這一點?
這裏是我的數據結構:
structure(list(suppressed = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 2L, 3L, 2L, 2L), .Label = c("full", "none", "partial"), class = "factor"), var1 = c(2, NA, 3, NA, 2, 3, 3, NA, 2, NA), var2 = c(6, 6, 7, NA, 6, 6, NA, 6, 7, NA)), .Names = c("suppressed", "var1", "var2"), row.names = c(NA, -10L), class = "data.frame")
只要'df [df $ suppress =='none'&is.na(df $ var1),「var1」] < - 0' –