Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert negative values to zero in dataframe in R

Tags:

r

I have a dataframe in R that I would like to convert all columns (outside the ids) from negative to zero

id1  id2  var1  var2  var3
-1   -1   0     -33     5
-1   -2   9     -10    -1

I can convert all columns with code line like:

temp[temp < 0] <- 0

But I can't adjust it to only a subset of columns. I've tried:

temp[temp < 0, -c(1,2)] <- 0

But this errors saying non-existent rows not allowed

like image 752
Sam Gilbert Avatar asked Dec 18 '15 09:12

Sam Gilbert


People also ask

How do I remove negative values from a DataFrame in R?

You can set them to NA which is "missing. And then you can use rowSums(..., na. rm=T) to ignore the NA values.

How do you treat negative values in R?

This can be done by using abs function. For example, if we have a data frame df with many columns and each of them having some negative values then those values can be converted to positive values by just using abs(df).

How do you change to zero in R?

To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0.


4 Answers

We can use data.table

setDT(d1)
for(j in grep('^var', names(d1))){
 set(d1, i= which(d1[[j]]<0), j= j, value=0)
}

d1
#    id1 id2 var1 var2 var3
# 1:  -1  -1    0    0    5
# 2:  -1  -2    9    0    0
like image 27
akrun Avatar answered Oct 13 '22 03:10

akrun


There might be fancier or more compact ways, but here's a vectorised replacement you can apply to the var columns:

mytable <- read.table(textConnection("
id1  id2  var1  var2  var3
-1   -1   0     -33     5
-1   -2   9     -10    -1"), header = TRUE)

mytable[, grep("^var", names(mytable))] <- 
    apply(mytable[, grep("^var", names(mytable))], 2, function(x) ifelse(x < 0, 0, x))
mytable
##    id1 id2 var1 var2 var3
##  1  -1  -1    0    0    5
##  2  -1  -2    9    0    0
like image 115
Ken Benoit Avatar answered Oct 13 '22 03:10

Ken Benoit


Edit a bit your variant

temp[,-c(1,2)][temp[, -c(1,2)] < 0] <- 0

like image 35
Batanichek Avatar answered Oct 13 '22 02:10

Batanichek


You can try using replace:

> mydf[-c(1, 2)] <- replace(mydf[-c(1, 2)], mydf[-c(1, 2)] < 0, 0)
> mydf
  id1 id2 var1 var2 var3
1  -1  -1    0    0    5
2  -1  -2    9    0    0
like image 39
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 13 '22 03:10

A5C1D2H2I1M1N2O1R2T1