Reputation: 7938
Suppose my data looks something like this (with many more columns)
set.seed(112116)
df <- data.frame(x1 = sample(c(LETTERS, -1:-10), 100, replace = T),
x2 = sample(c(letters, -1:-10), 100, replace = T),
x3 = sample(c(1:30, -1:-10), 100, replace = T))
I want to replace all negative numbers with NA. I can do it one by one like this:
df <- df %>% mutate(x1 = replace(x1, which(x1<0), NA),
x2 = replace(x2, which(x2<0), NA),
x3 = replace(x3, which(x3<0), NA))
But i'm hoping that there is a way of doing this for all columns in my data
Upvotes: 7
Views: 5954
Reputation: 887168
Try with mutate_each
df %>%
mutate_each(funs(replace(., .<0, NA)))
Or in the newer version of dplyr
version >= 1.00
df %>%
mutate(across(everything(), ~ case_when(.x >=0 ~ .x)))
Upvotes: 16