Ignacio Ignacio - 1 year ago 82
R Question

replace negative values with NA for all columns?

Suppose my data looks something like this (with many more columns)

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 Source

Try with mutate_each

df %>% 
    mutate_each(funs(replace(., .<0, NA)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download