Konrad Konrad - 4 years ago 711
R Question

Correct syntax for mutate_if

I would like to replace

NA
values with zeros via
mutate_if
in
dplyr
. The syntax below:

set.seed(1)
mtcars[sample(1:dim(mtcars)[1], 5),
sample(1:dim(mtcars)[2], 5)] <- NA

require(dplyr)

mtcars %>%
mutate_if(is.na,0)

mtcars %>%
mutate_if(is.na, funs(. = 0))


returns error:

Error in vapply(tbl, p, logical(1), ...) : values must be length 1,
but FUN(X[[1]]) result is length 32


What's the correct syntax for this operation?

Answer Source

The "if" in mutate_if refers to choosing columns, not rows. Eg mutate_if(data, is.numeric, ...) means to carry out a transformation on all numeric columns in your dataset.

If you want to replace all NAs with zeros in numeric columns:

data %>% mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download