user2957945
user2957945

Reputation: 2413

Apply a function over several columns

I am trying to use values from a look up table, to multiply corresponding values in a main table.

This is an example of some data

The look up

lu = structure(list(year = 0:12, val = c(1.6422, 1.6087, 1.5909, 1.4456, 
1.4739, 1.4629, 1.467, 1.4619, 1.2588, 1.1233, 1.1664, 1.1527, 
1.2337)), .Names = c("year", "val"), class = "data.frame", row.names = c(NA, 
-13L))

Main data

dt = structure(list(year = c(3L, 4L, 6L, 10L, 3L, 9L, 10L, 7L, 7L, 
1L), x = 1:10, y = 1:10), .Names = c("year", "x", "y"), row.names = c(NA, 
-10L), class = c("data.table", "data.frame"))

I can produce the results I want by merging and then multiplying one column at a time

library(data.table) 

dt = merge(dt, lu, by = "year")
dt[, xnew := x*val][, ynew := y*val]

However, I have many variables to apply this over. There have been many questions on this, but I cannot get it to work.

Using ideas from How to apply same function to every specified column in a data.table , and R Datatable, apply a function to a subset of columns , I tried

dt[, (c("xnew", "ynew")):=lapply(.SD, function(i) i* val), .SDcols=c("x", "y")]

Error in FUN(X[[i]], ...) : object 'val' not found

for (j in c("x", "y")) set(dt, j = j, value = val* dat[[j]])

Error in set(dt, j = j, value = val * dt[[j]]) : object 'val' not found

And just trying the multiplication without assigning (from Data table - apply the same function on several columns to create new data table columns) also didnt work.

dt[, lapply(.SD, function(i) i* val), .SDcols=c("x", "y")]

Error in FUN(X[[i]], ...) : object 'val' not found

Please could you point out my error. Thanks.

Im using data.table version v1.9.6.

Upvotes: 2

Views: 282

Answers (1)

akrun
akrun

Reputation: 887118

We can try by join and then by specifying .SDcols

dt[lu, on = .(year), nomatch =0 
    ][, c("x_new", "y_new") := lapply(.SD, `*`, val), .SDcols = x:y][]

Upvotes: 3

Related Questions