richpiana
richpiana

Reputation: 421

data.table multiplication columns by columns

i have a simple multiplication problem that does not lead to any warning but does not perform the right thing. I would like simply to add a column GDP_q0, GDP_q1 and GDP_q2 that is equal to price + unemployment + FX * CPI. Using data table the muliplication is not performed correctly (I dont know the behavior of data table in this situation). price, unemployment and cpi are always equal (price_q0 = price_q1 = price_q2)

test[, paste0('gdp_q', 0:2) := get(paste0('price_q', 0:2)) + get(paste0('unemployment_q', 0:2)) -
     get(paste0('FX_q', 0:2))*get(paste0('CPI_q', 0:2))]

This is doing the right thing

for(j in 0:2){ 
  nam= paste0('gdp_q', j)
  pf[, (nam) := pf$price + pf$unemployment- pf[[paste0('FX_q', j)]] * pf$CPI]
}

I believe it should be linked to a trick in the multiplication using data table.

Upvotes: 1

Views: 39

Answers (1)

akrun
akrun

Reputation: 886938

If we want to do this on multiple columns, loop over the columns with lapply or Map

priceq <- paste0('price_q', 0:2)
unemploymentq <- paste0('unemployment_q', 0:2)
Fxq <- paste0('FX_q', 0:2)
CPIq <- paste0('CPI_q', 0:2)
f1 <- function(x, y, u, v) x + y - u * v

test[, paste0('gdp_q', 0:2) := Map(f1, mget(priceq), 
          mget(unemploymentq), mget(Fxq), mget(CPIq))]

Upvotes: 1

Related Questions