【问题标题】:Create a variable in R that indicates whether numeric "subgroup" rows sum to "total" rows by group在 R 中创建一个变量,指示数字“子组”行是否按组总和为“总”行
【发布时间】:2021-05-04 23:15:33
【问题描述】:

我希望能够创建一个逻辑变量,用于指示对于特定类别,一组子组行(即“组”变量中的 A、B、C)的计数总和是否相同值作为我的“全部”/整体组行。

我的数据如下:

group = c("All", "A", "B", "C", "All", "A", "B", "C")
category = c("music", "music", "music", "music", "movies", "movies", "movies", "movies")
count = c(120, 15, 75, 30, 250, 36, 28, 72)

data <- data.frame(cbind(group, category, count))

我想要的是添加“sum_to_all”列,如:

sum_to_all = c(TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE)

data <- data.frame(cbind(group, category, count, sum_to_all))

在这种情况下,对于音乐类别,“计数”变量子组“A”、“B”和“C”总和为“全部”组中的计数 (TRUE),但对于电影则不是 (FALSE)类别。

我知道我可以将数据集重新调整为宽,其中每个组都有自己的“计数”列并比较列,但我想知道是否有一个简单的逐行解决方案。提前致谢。

【问题讨论】:

  • 顺便说一句,data.frame(cbind(group, category, count)) 将您的所有数字转换为文本,因为cbind 首先是matrix。你可以跳过那部分,直接做data.frame(group, category, count)

标签: r data-wrangling rowwise


【解决方案1】:

我们可以按“类别”分组并通过比较“计数”的sum(不包括第一个观察值)与first 观察值来创建“sum_to_all”

library(dplyr)
data %>%
    group_by(category) %>%
    mutate(sum_to_all = sum(count[-1]) == first(count)) %>%
    ungroup

-输出

# A tibble: 8 x 4
#  group category count sum_to_all
#  <chr> <chr>    <dbl> <lgl>     
#1 All   music      120 TRUE      
#2 A     music       15 TRUE      
#3 B     music       75 TRUE      
#4 C     music       30 TRUE      
#5 All   movies     250 FALSE     
#6 A     movies      36 FALSE     
#7 B     movies      28 FALSE     
#8 C     movies      72 FALSE  

注意:这里我们假设 'All' 'group' 为 first 元素。如果并非总是如此,请使用arrange 或使用== 进行子集处理

data %>%
    group_by(category) %>%
    mutate(sum_to_all = sum(count[group != 'All']) ==count[group == 'All']) %>%
    ungroup

数据

data <- data.frame(group, category, count)

【讨论】:

  • 谢谢。如果我只想要 A 组和 B 组的总和进行比较,你知道我如何排除“All”和“C”吗?
  • @mkpcr 在这种情况下,您可以使用[! group %in% c("All", "C")][group %in% c("All", "C")] 在第二个解决方案中替换
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2020-12-29
  • 2020-07-14
  • 1970-01-01
  • 2022-08-22
相关资源
最近更新 更多