Home > Enterprise >  How can I do mathematical operations of a subset of data in data table?
How can I do mathematical operations of a subset of data in data table?

Time:02-20

As the question says, I want to modify a subset of data.

Example:

library(data.table)
v1 <- rep(c(4.5, 3.5, 4.0, 1.0, 4.0, 3.5, 4.5, 4.0, 1.0, 4.0, 
             3.0, 4.5, 4.0, 3.0, 1.5, 1.5, 2.0, 2.0,
             3.5, 4.5, 3.5, 3.5, 4.0, 3.0, 4.0, 4.0, 2.5, 4.5),100)
v2 <- rep(c(4.5, 3.5, 1.5, 1.0, 4.0, 1.5, 4.5, 1.5, 1.0, 4.0, 
            3.0, 1.5, 1.5, 3.0, 1.5, 1.5, 2.0, 2.0,
            3.5, 1.5, 3.5, 3.5, 1.5, 3.0, 4.0, 4.0, 2.5, 4.5),100)

dt <- data.table(v1, v2)

Then I want to slice out a subset and do mathematical operations on it, but dont want to change the rest of the data.

I am looking for something like followed:

dT <- dT[v1 <= 5.0 & v1 > 4.4] * 100

CodePudding user response:

Please find below one possible solution.

Reprex

  • Code
library(data.table)

dt[v1 <= 5.0 & v1 > 4.4] <- dt[, .SD[v1 <= 5.0 & v1 > 4.4] * 100]
  • Output
dt
#>          v1    v2
#>    1: 450.0 450.0
#>    2:   3.5   3.5
#>    3:   4.0   1.5
#>    4:   1.0   1.0
#>    5:   4.0   4.0
#>   ---            
#> 2796:   3.0   3.0
#> 2797:   4.0   4.0
#> 2798:   4.0   4.0
#> 2799:   2.5   2.5
#> 2800: 450.0 450.0

Created on 2022-02-20 by the reprex package (v2.0.1)

CodePudding user response:

Subset the rows and multiply all columns by a constant and save the result:

dt <- dt[v1 <= 5.0 & v1 > 4.4, lapply(.SD, \(x) x * 100)] 

If you want to modify in-place just the selected rows you could:

dt[v1 <= 5.0 & v1 > 4.4, (names(dt)) := lapply(.SD, \(x) x * 100)] 
  • Related