I would like to replace 0 in my data.frame with 1, but only in factor columns, which have only 3 values (0, 1 or NA). I have to avoid also specifying columns by names as my real data set is pretty large and it would be cumbersome. So I thought I could make use of dplyr::mutate_if and try something like:
df %>% mutate_if(~(is.factor(.) & (unique(.) %in% c(0, 1, NA))), ~replace(., . == 0, 1))
but ended up with following error:
Error in selected[[i]] <- .p(.tbl[[vars[[i]]]], ...) : more elements supplied than there are to replace
What is wrong with this formula? How can I make use of dplyr to replace 0 with 1?
My example dataset looks like below:
df <- structure(list(a1 = structure(c(1L, NA, NA, 2L, NA, 1L, NA), .Label = c("0",
"1"), class = "factor"), a2 = structure(c(NA, NA, NA, 1L, NA,
NA, NA), .Label = "1", class = "factor"), a3 = structure(c(NA,
1L, 2L, 3L, NA, 4L, 2L), .Label = c("0", "1", "2", "6"), class = "factor"),
a4 = structure(c(1L, 1L, NA, NA, NA, NA, 1L), .Label = "0", class =
"factor"),
a5 = c(0L, 1L, 1L, NA, 1L, 0L, NA)), .Names = c("a1", "a2",
"a3", "a4", "a5"), class = c("tbl_df", "tbl", "data.frame"), row.names =
c(NA, -7L))