Ignacio Ignacio - 18 days ago 5
R Question

replace negative values with NA for all columns?

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

Answer

Try with mutate_each

df %>% 
    mutate_each(funs(replace(., .<0, NA)))