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]
You can't, it is only possible once.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With