【问题标题】:Alternative to aggregate function that doesn't collapse df替代不折叠 df 的聚合函数
【发布时间】:2016-10-26 20:42:15
【问题描述】:

我有个人级别的数据,并想创建一个包含家庭中孩子数量的新变量。我为孩子创建了一个虚拟变量(如果年龄

 No_kids <- aggregate(child ~ HH_ID, data = df, sum)

此代码有效,但数据框崩溃了,而我想将孩子的数量分配给该家庭的每个观察值。是否有不折叠数据集的聚合函数的替代方法?

【问题讨论】:

  • 查看ave 并阅读minimal reproducible example,了解如何在 SO 上提问。
  • 如果您根据HH_ID 将 No_kids 数据框与您的原始数据框重新合并,这不会得到您想要的吗?

标签: r count aggregate


【解决方案1】:

另一个选项是 dplyr ...当然

library(dplyr)
> player_df = data.frame(team = c('ARI', 'BAL', 'BAL', 'CLE', 'CLE'),
+                        player =c('A', 'B', 'C', 'D', 'F'), 
+                        '1' = floor(runif(5, min=1, max=2)*10),
+                        '2' = floor(runif(5, min=1, max=2)*10))

然后使用 group_by 并从 dplyr 变异

player_df %>% group_by(team) %>% mutate(count = n())

Source: local data frame [5 x 5]
Groups: team [3]

    team player    X1    X2 count
  <fctr> <fctr> <dbl> <dbl> <int>
1    ARI      A    12    12     1
2    BAL      B    10    12     2
3    BAL      C    14    12     2
4    CLE      D    10    14     2
5    CLE      F    18    17     2

【讨论】:

  • 啊,太慢了一秒钟:)
  • 你应该小心使用 n() ,因为 OP 在他们的 HH_ID 组中既有零也有一个,它们都将被 n() 计数
【解决方案2】:

或者,您可以在聚合后执行merge(因此在基础 R 中):

ag <- aggregate(child ~ HH_ID, data = df, sum)
setNames(merge(df, ag, by="HH_ID"), c("HH_ID", "child", "No_kids"))

【讨论】:

  • 不是最优雅的代码,但调整你的建议是有效的:ag
【解决方案3】:

使用dplyr 包:

# Create sample data
set.seed(3252)

df <- data.frame(
  HH_ID = sample(1:10, 50, replace = TRUE),
  child = sample(0:1, 50, replace = TRUE)
)

# Count number of children
df %>% 
  group_by(HH_ID) %>% 
  mutate(child_count = sum(child)) %>% 
  ungroup()

【讨论】:

    猜你喜欢
    • 2023-01-10
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2016-10-26
    • 2017-01-03
    相关资源
    最近更新 更多