I have a tibble
object and I want to replace all of the columns except certain ones with a value (say NA
or 0
). I can able to do it without pipes %>%
but how can I do it with %>%
?
library(tibble)
dtf <- tibble(id = c('12', '22', '33', '40'),
x1 = c(0, 2, 3, 4),
a2 = c(1, 0, 3, 0),
c5 = c('a', 'b', 'c', 'd'))
# This raises an error:
dtf %>% select(-id) <- NA
Error in dtf %>% select(-id) <- NA : could not find function "%>%<-"
# This works:
dtf[, colnames(dtf) != 'id'] <- NA
dtf
# A tibble: 4 x 4
id x1 a2 c5
<chr> <lgl> <lgl> <lgl>
1 12 NA NA NA
2 22 NA NA NA
3 33 NA NA NA
4 40 NA NA NA
I believe I should use mutate()
or mutate_all()
but I couldn't figure out. One similar SO answer offered na_if()
for NA
values but I cannot make it work for this case.