Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace negative values with NA for all columns?

Tags:

r

dplyr

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

like image 911
Ignacio Avatar asked Nov 21 '16 15:11

Ignacio


People also ask

How do I change column values in NA?

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.

How do I replace negative numbers in R?

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).


1 Answers

Try with mutate_each

df %>% 
    mutate_each(funs(replace(., .<0, NA)))
like image 161
akrun Avatar answered Sep 28 '22 22:09

akrun