Convert negative values to zero in dataframe in R

后端 未结 5 1967

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         


        
相关标签:
5条回答
  • 2021-01-05 01:25

    You could use pmax:

    dat <- data.frame(id1=c(-1,-1), id2=c(-1,-2), var1=c(0,9), var2=c(-33,10), var3=c(5,-1))
    dat[,-c(1,2)] <- matrix(pmax(unlist(dat[,-c(1,2)]),0), nrow=nrow(dat))
    
    0 讨论(0)
  • 2021-01-05 01:38

    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
    
    0 讨论(0)
  • 2021-01-05 01:44

    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
    
    0 讨论(0)
  • 2021-01-05 01:45

    Edit a bit your variant

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

    0 讨论(0)
  • 2021-01-05 01:50

    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
    
    0 讨论(0)
提交回复
热议问题