Serkan
Serkan

Reputation: 1945

Multiply Rows Conditionally in data.table

I have the following data.table

# Load Library
library(data.table)

# Generate Data

test_data <- data.table(
  year = c(2000,2000,2001,2001),
  grp  = rep(c("A","B"),2),
  value = 1:4
)

I want to multiply the values of group A with varying parameters over year. My attempt was using sapply with fifelse and a fixed value of 2, but it seems that this solutions is going to be messy if I want to vary this value over time.

multiply_effect <- sapply(
  1:nrow(test_data), function(i){
    
    fifelse(
      test = test_data$grp[i] == "A", test_data$value[i] * 2, test_data$value[i]
    )
  }
)

Lets say that I want to multiply the value of grp A with 2 in 2000 and by 3 in 2001 and keeping grp B as it is, then my desired outputwould be,

   year grp value new_value
1: 2000   A     1         2
2: 2000   B     2         2
3: 2001   A     3         9
4: 2001   B     4         4

Im looking for at data.table-solution only.

Upvotes: 0

Views: 167

Answers (1)

Waldi
Waldi

Reputation: 41210

You could define the factors for the years / groups you want to modify in another lookup data.table and update the main table with a join:

test_data <- data.table(
  year = c(2000,2000,2001,2001),
  grp  = rep(c("A","B"),2),
  value = 1:4
)

factor_lookup <- data.table(
  year = c(2000,2001),
  grp  = rep("A",2),
  factor = c(2,3)
)


test_data[factor_lookup ,value:=value*factor,on=.(year,grp)][]

    year    grp value
   <num> <char> <int>
1:  2000      A     2
2:  2000      B     2
3:  2001      A     9
4:  2001      B     4

Upvotes: 1

Related Questions