2
我使用tidyr::complete()
在包含多列的數據框中包含缺失行,從而生成NAs值。如果我沒有明確的列名稱列表,我如何指示fill
選項將NA值替換爲0?R/tidyr :: complete - 動態填充缺失值
例子:
df <- data.frame(year = c(2010, 2013:2015),
age.21 = runif(4, 0, 10),
age.22 = runif(4, 0, 10),
age.23 = runif(4, 0, 10),
age.24 = runif(4, 0, 10),
age.25 = runif(4, 0, 10))
# replaces missing values with NA - not what I want
df.complete <- complete(df, year = 2010:2015)
# replaces missing values with 0 - works, but needs explicit list
df.complete <- complete(df, year = 2010:2015, fill = list(age.21 = 0, age.22 = 0,
age.23 = 0, age.24 = 0,
age.25 = 0))
# throws error (is.list(replace) is not TRUE)
df.complete <- complete(df, year = 2010:2015, fill = 0)
# replaces missing values with NA - not what I want
df.complete <- complete(df, year = 2010:2015, fill = list(rep(0,6)))
一種解決方法可以是使用df.complete[is.na(df.complete)] <- 0
,但熊替換值過多的危險。