Using..col in j expression in data.table

I am having trouble getting the desired behavior from the syntax ..jin the latest version data.table, when I want to query a column using a variable in the column area and then manipulate that variable. As an example, here is a table:

A <- data.table(myValA = c(6,23,7,2,5), myValB = c(43,12,7,89,2))
valA <- "myValA"
valB <- "myValB"

I want to get an element by elements from two columns:

A[, myValA * myValB]

[1] 258 276  49 178  10

But I want to call columns by reference using variables in the call area, valAand valB. For easy access to variables, the syntax ..valAworks fine.

A[, ..valA]

   myValA
1:      6
2:     23
3:      7
4:      2
5:      5

and similarly for ..valB. But when I try to multiply two columns in j, using either the old style with=Falseor the new style command ..j, I get errors:

A[, ..valA * ..valB]
Error in eval(jsub, SDenv, parent.frame()) : object '..valA' not found

A[, valA * valB, with = FALSE]
Error in valA * valB : non-numeric argument to binary operator

What am I missing here?

UPDATE:

( ), , . , , .

+4
1

.SDcols, Reduce

A[, Reduce(`*`, .SD), .SDcols = c(valA, valB)]
#[1] 258 276  49 178  10

v1 <- c(valA, valB)
A[,  ..v1][, do.call(`*`, .SD)]
#[1] 258 276  49 178  10

(A[, ..valA] * A[, ..valB])[[1]]
#[1] 258 276  49 178  10
+2

Source: https://habr.com/ru/post/1677028/


All Articles