【问题标题】:R - Group by a value and calculate the percentage of the whole groupR - 按一个值分组并计算整个组的百分比
【发布时间】:2018-10-08 15:28:10
【问题描述】:

编辑:我的问题不够清楚。我道歉。

问题是定义组并将数据框的列的值分配给它。 我自己用 ifelse 链和 cmets 解决了这个问题。感谢那。然后我分别为每一列手动完成。

data %>% 
  mutate(group = ifelse(richness <= -0.6, "1",
                        ifelse(richness > -0.6 & richness <= -0.2, "2",
                               ifelse(richness >-0.2 & richness <= 0.2, "3",
                                      ifelse(richness >0.2 & richness <= 0.6, "4",
                                             ifelse(richness >0.6, "5", NA)))))) %>%
                          group_by(group) %>% 
                          summarise(percentage=n()*100/"No.of.values")

【问题讨论】:

  • 使用table(df$var)
  • 作为旁注,您可以使用dplyr 的函数case_when() 来避免嵌套ifelse() 以获得更清晰的代码;)

标签: r aggregate tabulate


【解决方案1】:

mtcars数据集中的carb变量为例:

prop.table(table(mtcars$carb)) * 100

     1      2      3      4      6      8
21.875 31.250  9.375 31.250  3.125  3.125

如果您想自己定义组,可以使用cut 函数:

groups <- c(0,2,6,8) # interval values for the groups
prop.table(table(cut(mtcars$carb, breaks=groups))) * 100

 (0,2]  (2,6]  (6,8]
53.125 43.750  3.125

【讨论】:

  • OP 表示涉及多个列,所以可能类似于 addmargins(table(Map(cut, DF[cols], breaks = groups_list)))
  • @Frank 你可能是对的。从现在提出问题的方式来看,最终目标是什么并不是 100% 清楚的。而且标题让我更不清楚。
【解决方案2】:

工作流程。

  • 添加一个虚拟列;
  • 按虚拟列分组;
  • 计算子组。

以下是一些示例代码:

require(dplyr)

# generate fake data.
set.seed(123456)

sample <-  data.frame(Nums = rep(NA,100))
sample$Nums <- sample(-100:100, 100, replace = T)/100 
size <- length(sample$Nums)

# add dummy column
sample <- sample %>% 
  # changed the dummy column accordingly
  mutate(dummy = ifelse(Nums < 0, "A", "B")) %>% 
  # group nums
  group_by(dummy) %>% 
  # calculate percentage
  summarise(percentage = n()*100/size)

head(sample)

# A tibble: 2 x 3
  dummy count percentage
  <chr> <int>      <dbl>
1 A        50         50
2 B        50         50

【讨论】:

  • 这很有帮助,谢谢文龙!一个问题仍然存在:我有大约 30 列和 6 个组。如果我为每个列和组手动执行此操作,则将需要很长时间。有没有办法定义一次组(每列都相同),然后循环遍历所有列?谢谢!!
  • @Heiko,在这种情况下,带有样本数据的可重现示例将非常有帮助。
猜你喜欢
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2019-02-09
  • 1970-01-01
相关资源
最近更新 更多