In a previous question Return a list in dplyr mutate() it was clairified that although dlpyr cannot in release 0.2 create new variables from a vector returned by a function, data.table() can with the syntax -:
it[, c(paste0("V", 4:5)) := myfun(V2, V3)]
If the function myfun
from that question is altered to -:
myfun = function(arg1,arg2) {
if (arg1 > arg2) {
temp1 = arg1 + arg2
temp2 = arg1 - arg2 }
else {
temp1 = arg1 * arg2
temp2 = arg1 / arg2 }
list(temp1,temp2)
}
the solution posted above returns a warning -:
it = data.table(c("a","a","b","b","c"),c(1,2,3,4,5), c(2,3,4,2,2))
it[, c(paste0("V", 4:5)) := myfun(V2, V3)]
Warning message:
In if (arg1 > arg2) { :
the condition has length > 1 and only the first element will be used
This implies that somehow data.table() is passing more than a single row to the function. Why is this occurring?
myfun(it$V2, it$V3)
gives the same warning. It's because you are comparing two vectors (of length > 1) when doingarg1 > arg2
. So, it takes just the first value (and provides the warning). – Arun