Pekka
Pekka

Reputation: 2448

Using function result again in j expression

How can I do this without calculating the sum and prod functions two times?

require(data.table)

DT = data.table(x=rep(c("a","b","c"),each=4), y=1:6, V1 = 1000L, V2 = 2000, V3 = 1)

DT[x != "c",":="(
    V1 = sum(y),
    V2 = prod(y),
    V3 = sum(y) + prod(y)
),by=x]

Of course I can just drop the V3 calculation and then continue like this:

DT[x != "c",V3 := V1 + V2]

But it's not very clean and furthermore the i-expression needs to be evaluated again.

My desired syntax is something like this:

DT[x != "c",":="(
    V1 = sum(y),
    V2 = prod(y),
    V3 = V1 + V2
),by=x]

Upvotes: 5

Views: 73

Answers (1)

agstudy
agstudy

Reputation: 121578

You can use {..} to define your expression and store intermediate variable before returning result :

DT[x != "c", c("V1","V2","V3") := 
     {  V1 <- sum(y) 
        V2 <- prod(y)        
        V3 <- V1 + V2    
        list(V1,V2,V3)},by=x]

Upvotes: 9

Related Questions