Getting one row per group in R data.table
I often want to process one row of a data table at a time. I used
d[, j, by=rownames(d)]
but that doesn't always work (there is an error message sometimes as it evaluates column names) and it's not a very clean expression of what I'm trying to do anyway.
Let me give you a specific example.
d = data.table(a=c(1,2),b=c(3,4))
f = function(x,y) x[1]+y[1] #expects length 1 vectors x and y and adds them
d[, id := 1:.N]
d[, f(a,b), by=id]
d[, id := NULL]
The situation is that I have a function f that is not vectorized. I decorated d with an id column so that I can process one row at a time. I am looking for the best way to do this.
Here's another example, without the f function:
d[, list(a=a,b=b,s=a:b), by = id]
d[, id := NULL]
+3
source to share
No one has answered this question yet
Check out similar questions: