I'm using tidyr::complete()
to include missing rows in a data frame with many columns, leading to NAs values. How can I instruct the fill
option to replace the NA values with 0 if I don't have an explicit list of column names?
Example:
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)))
A workaround could be to use df.complete[is.na(df.complete)] <- 0
, but that bears the danger of replacing too many values.