zlu15
zlu15

Reputation: 55

Multiply columns in a DT by DT[i,j]

Question 1: line 1 throws an error. Why and how to multiply all columns by DT[i,j]? Question 2: line 2 works but are there better ways to multiply all other columns by one column?

df=data.table(matrix(1:15,3,5))
df[ , lapply(.SD, function(x) {x*df$V5), .SDcols = c("V1","V2","V3","V4")] #line 1
df[ , lapply(.SD, function(x) {x*df[1,"V5"})}, .SDcols = c("V1","V2","V3","V4")] #line 2

Upvotes: 1

Views: 97

Answers (1)

akrun
akrun

Reputation: 887501

As we are multiplying one column with the rest, either do the multiplication of the Subset of Data.table directly

df[, .SD * V5, .SDcols = V1:V4]

Or with lapply

df[,  lapply(.SD, `*`, V5), .SDcols = V1:V4]

Note that in both cases, we are not updating the original dataset columns. For that we need :=

df[, paste0("V", 1:4) := .SD * V5, .SDcols = V1:V4]

In the OP's code, there is a closing } missing in the line 1

df[ , lapply(.SD, function(x) {x*df$V5), .SDcols = c("V1","V2","V3","V4")] 
                                      ^^

It would be

df[, lapply(.SD, function(x) { x* V5 }), .SDcols = V1:V4]

Here, we don't really need those curlies as well as within the data.table, column names can be referenced as unquoted instead of df$ along with the shortened version of .SDcols where column names are represented as a range (:)

Upvotes: 4

Related Questions