Tsvetan Nikolov Tsvetan Nikolov - 2 months ago 11
R Question

Getting a vector when doing j by group

I have a very trivial question I can't find the answer for.
Using the mtcars data:

library(data.table)
data(mtcars)
mtcars<-as.data.table(mtcars)
mtcars <- mtcars[,.N, by=cyl]
mtcars

cyl N
1: 6 7
2: 4 11
3: 8 14


Can I directly get the N column as a vector, rather than as a column of a data.table?

Answer

Try this:

> library(data.table)
> data(mtcars)
> mtcars<-as.data.table(mtcars)
> mtcars <- mtcars[,.N, by=cyl]$N
> mtcars
[1]  7 11 14