What does “.N” means in data table in r?

后端 未结 1 1397
余生分开走
余生分开走 2021-01-31 20:13

I have a data table dt:

library(data.table)
dt = data.table(a=LETTERS[c(1,1:3)],b=4:7)

   a b
1: A 4
2: A 5
3: B 6
4: C 7

The res

相关标签:
1条回答
  • 2021-01-31 20:55

    Think of .N as a variable for the number of instances. For example:

    dt <- data.table(a = LETTERS[c(1,1:3)], b = 4:7)
    
    dt[.N] # returns the last row
    #    a b
    # 1: C 7
    

    Your example returns a new variable with the number of rows per case:

    dt[, new_var := .N, by = a]
    dt
    #    a b new_var
    # 1: A 4       2 # 2 'A's
    # 2: A 5       2
    # 3: B 6       1 # 1 'B'
    # 4: C 7       1 # 1 'C'
    

    For a list of all special symbols of data.table, see also https://www.rdocumentation.org/packages/data.table/versions/1.10.0/topics/special-symbols

    0 讨论(0)
提交回复
热议问题