Reputation: 32466
For extracting levels from a data.table, is the standard way to lapply over the data.table
as a list or do it inside the brackets somehow?
For example, using the npk
builtin data, I know that the first 4 columns are factors and I want to extract the levels.
dat <- as.data.table(npk)
This is what I want, a list of the levels
levs <- lapply(dat[,1:4,with=FALSE], levels)
But, am I missing the data.table
way that would be something like this? (this isnt right though because it repeats the levels to match the longest one).
levs2 <- dat[, lapply(.SD, levels), .SDcols=names(dat)[1:4]]
ps. sorry if this seems dumb, I am just trying to pick up the proper data.table idioms.
Upvotes: 2
Views: 1248
Reputation: 6372
Your first example seems reasonable to me, and I don't think that you can do it within the brackets of the data.table, as the return type should be a list.
Another option is Filter(Negate(is.null),lapply(DT,levels))
, which has the added benefit of not needing to know which columns are factors beforehand
Upvotes: 2