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
r data.table


source to share


No one has answered this question yet

Check out similar questions:

629
data.table vs dplyr: can something do good and other do bad or bad?
362
Why is '' '' better than 'subset'?
105
How to remove a row by reference in data.table?
83
What is the purpose of setting a key in data.table?
eleven
the grouping column data.table has a length of 1 in "J"
4
Rotate vector output to columns in data.table along with other columns?
1
strange behavior of data.table when grouped by all columns in data.table
0
Running distVincentyEllipsoid () on each row of data.table
0
r - getting vectors from strings in data.table
0
R - data.table, not grouping when used with



All Articles
Loading...
X
Show
Funny
Dev
Pics