gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:22:04 25 4
gpt4 key购买 nike

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

Property    Type
1 apartment
1 office
2 office
2 office
3 apartment
3 apartment
3 office

我现在想按属性(property)计算办公室和公寓:
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

我试过
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")

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

最佳答案

您可以按如下方式解决:

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

关于r - 按组计算具有某些值的数据表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60655464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com