Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function result again in j expression

Tags:

r

data.table

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]
like image 584
Pekka Avatar asked Jan 28 '15 17:01

Pekka


People also ask

Can you use return twice in a function?

You can't, it is only possible once.

How do I return a result from a function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.

What value is returned by function result?

A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.

What happens when a function is returned?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.


1 Answers

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]
like image 100
agstudy Avatar answered Nov 05 '22 00:11

agstudy