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
You can replace NA values with zero(0) on numeric columns of R data frame by using is.na() , replace() , imputeTS::replace() , dplyr::coalesce() , dplyr::mutate_at() , dplyr::mutate_if() , and tidyr::replace_na() functions.
To convert negative values in a matrix to 0, we can use pmax function. For example, if we have a matrix called M that contains some negative and some positive and zero values then the negative values in M can be converted to 0 by using the command pmax(M,0).
Try with mutate_each
df %>%
mutate_each(funs(replace(., .<0, NA)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With