按组计算具有某些值的数据表中的行

las*_*r.p 5 r data.table

我有一个看起来像这样的数据表:

Property    Type
1           apartment
1           office
2           office
2           office
3           apartment
3           apartment
3           office
Run Code Online (Sandbox Code Playgroud)

我现在想按财产计算办公室和公寓:

Property    Type       number_of_offices    number_of_apartments
       1    apartment                  1                       1
       1    office                     1                       1
       2    office                     2                       0
       2    office                     2                       0
       3    apartment                  1                       2
       3    apartment                  1                       2
       3    office                     1                       2
Run Code Online (Sandbox Code Playgroud)

我试过

my.DT <- myDT[,.(Type=Type, number_of_offices=nrow(my.DT[my.DT$Type=="office",]), number_of_apartments=nrow(my.DT$Type=="apparment",], by="Property")
Run Code Online (Sandbox Code Playgroud)

但是,这只给了我整个数据表的总数。有没有人有办法解决吗?

B. *_*ang 4

您可以按如下方式解决:

cols <- c("number_of_offices", "number_of_apartments")
df[, (cols) := .(sum(Type == "office"), sum(Type == "apartment")), Property]

# Property      Type number_of_offices number_of_apartments
# 1:        1 apartment                 1                    1
# 2:        1    office                 1                    1
# 3:        2    office                 2                    0
# 4:        2    office                 2                    0
# 5:        3 apartment                 1                    2
# 6:        3 apartment                 1                    2
# 7:        3    office                 1                    2
Run Code Online (Sandbox Code Playgroud)