【问题标题】:Summarize data based on unique ID column根据唯一 ID 列汇总数据
【发布时间】:2021-04-29 05:18:52
【问题描述】:

我正在尝试根据 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))

【问题讨论】:

    标签: r dplyr tidyverse unique tapply


    【解决方案1】:

    您可以使用across()summarise() 中同时处理多个变量。在你的情况下:

    df %>% 
      group_by(ID) %>% 
      summarise(across(myvars, max)) %>% 
      summarise(across(myvars, sum))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多