How to explicitly name the count column generated by the .N function?

Viewed 3992

I want to group-by a data table by an id column and then count how many times each id occurs. This can be done as follows:

dt <- data.table(id =  c(1, 1, 2))
dt_by_id <- dt[, .N, by = id] 

dt_by_id
   id N
1:  1 2
2:  2 1

That's pretty fine, but I want the N-column to have a different name (e. g. count). In the help it says:

.N is an integer, length 1, containing the number of rows in the group. This may be useful when the column names are not known in advance and for convenience generally. When grouping by i, .N is the number of rows in x matched to, for each row of i, regardless of whether nomatch is NA or 0. It is renamed to N (no dot) in the result (otherwise a column called ".N" could conflict with the .N variable, see FAQ 4.6 for more details and example), unless it is explicitly named; ... .

How to "explicitly name" the N-column when creating the dt_by_id data table? (I know how to rename it afterwards.) I tried

dt_by_id <- dt[, count = .N, by = id]

but this led to

Error in `[.data.table`(dt, , count = .N, by = id) : 
  unused argument (count = .N)
2 Answers

You have to list the output of your calculation if you want to give your own name:

dt[, .(count=.N), by = id]

This is identical to dt[, list(count=.N), by = id], if you prefer; . is an alias for list here.

If we have already named it, then use setnames

setnames(dt_by_id, "N", 'count')

or using rename

library(dplyr)
dt_by_id %>%
   rename(count = N)
#  id count
#1:  1     2
#2:  2     1
Related