1

I have a data.table and I want to multiply all the values in column 1 by the first element of a vector, then multiply all the values in column 2 by the 2nd element of the vector, etc...

dt <- data.table(col1=c(1,1,1,1), col2=c(2,2,2,2), col3=c(3,3,3,3))
v <- c(1,2,3)

For a data.frame I would do

dt.new <- sapply(1:ncol(dt), function(i) dt[, i] * vec[i])

But it doesn't work like this for data.table. I tried

cols <- c("col1", "col2", "col3")
dt.new <- dt[, (cols):= lapply(.SD, function(i) dt[[i]]*v[i]), .SDcols = cols]

It does not work either. How can I do this?

beni
  • 180
  • 1
  • 1
  • 8
  • Regarding why your approach failed: [`.SD` is a `data.table`](https://stackoverflow.com/questions/8508482/what-does-sd-stand-for-in-data-table-in-r/47406952#47406952) and hence ultimately a `list` from `lapply` perspective. So `lapply(.SD, f)` will apply `f` to each _column_ of `.SD`. – MichaelChirico Nov 15 '18 at 12:12
  • 2
    Also `dt * v[col(dt)]` and such – David Arenburg Nov 15 '18 at 12:13

1 Answers1

8

Map was designed for this:

dt[, Map("*", .SD, v)]
#   col1 col2 col3
#1:    1    4    9
#2:    1    4    9
#3:    1    4    9
#4:    1    4    9

Also works with a data.frame:

DF <- as.data.frame(dt)
as.data.frame(Map("*", DF, v))
#  col1 col2 col3
#1    1    4    9
#2    1    4    9
#3    1    4    9
#4    1    4    9
Roland
  • 127,288
  • 10
  • 191
  • 288