tobinz
tobinz

Reputation: 335

Use data.table to change columns' values

I have a dataset dft consisting of variables name, weight, height like the following

name <- c("Bob","Mary","Jane","Kim")
weight <- c(60,65,45,55)
height <- c(170,165,140,135)
dft <- data.table(name,weight,height,) 

Now for Bob, I want to add 10 to its weight and 12 to its height. I tried this:

dft[, c("weight","height") := lapply( .SD,  function(x){  
                             if (x == c(60,170) ) {
                                x = c(70,182)
                             }
                                  }), .SDcols = grep("eight$",names(dft)) ]

but it's not working. Warnings and errors have repeatedly appeared. I wish to use lapply to do it. Any suggestion is appreciated.

Upvotes: 1

Views: 51

Answers (1)

akrun
akrun

Reputation: 887881

We can use fifelse with Map (assuming that we are matching the values)

library(data.table)
dft[, c("weight","height") := Map(function(x, y) 
    fifelse(x %in% c(60, 170), x + y, x), .SD, c(10, 12)),
      .SDcols =  patterns('eight$')][]

-output

#    name weight height
#1:  Bob     70    182
#2: Mary     65    165
#3: Jane     45    140
#4:  Kim     55    135

Or if it is based on the value of 'name'

dft[name == 'Bob', c('weight', 'height') :=
       .SD + list(10, 12), .SDcols = patterns("eight$")]

data

dft <- data.table(name,weight,height) 

Upvotes: 2

Related Questions