我正在尝试根据 ID 列汇总多个列,因此我不会重复计算观察值。我已经设法使用 tapply
一次获取一个变量所需的内容,但无法同时为多个变量执行此操作。
此外,我想应用它的数据框有 +50,000 行,我想将它应用到 +10 个不同的计数变量。我想知道 dplyr
中是否有更好的解决方案,因为我最终想用这些数据创建一个闪亮的仪表板。
我复制了一小部分数据样本并显示了现有成本。
#Creating data frame
df <- data.frame (ID = c(1, 1, 2, 3, 4, 4, 4),
Count = c(1, 1, 30, 15, 1, 1, 1),
Count2 = c(1, 1, 20, 10, 1, 1, 1),
Service = c("Service A", "Service B", "Service C", "Service D",
"Service E", "Service F", "Service G"))
#Create object of variables to count
myvars <- c("Count", "Count2")
#Count number of unique frequencies for two groups
df %>%
group_by(ID) %>%
summarise(value_sum = sum(tapply(myvars, ID, FUN = max))) %>%
summarise(value_sum = sum(value_sum))
#Count number of unique frequencies (code works for one variable at a time)
df %>%
group_by(ID) %>%
summarise(value_sum = sum(tapply(Count, ID, FUN = max))) %>%
summarise(value_sum = sum(value_sum))
df %>%
group_by(ID) %>%
summarise(value_sum = sum(tapply(Count2, ID, FUN = max))) %>%
summarise(value_sum = sum(value_sum))
答案 0 :(得分:0)
您可以使用 across()
在 summarise()
内同时处理多个变量。在你的情况下:
df %>%
group_by(ID) %>%
summarise(across(myvars, max)) %>%
summarise(across(myvars, sum))