有什么方法可以让变量按 group_by 分组?

Any way to keep variables grouped by group_by?

我有一个数据框,其中包含一个位置列和一个县列,显示一组县的不同位置的数据。我正在按 County 列分组以进行另一次计算,但我想保留一种方法来查看每个 County 中包含哪些位置。这可能吗?

这是原始数据的示例:

location   county   x   y
hend       hender   2   10
alam       alam     0   5
alex       alam     4   3
alleg      allegy   6   1
ann        hender   9   0

这也是我更改的内容:

df <- df %>%
  group_by(county) %>%
  summarise(total = sum(x + y))

county   total
hender   17
alam     12
allegy   7

同样,不确定这是否可行,但我希望第三列(我们称之为 allloc)显示每个县的位置,如果可能的话用逗号分隔。像这样:

county   total   allloc
hender   17      hend, ann
alam     12      alam, alex
allegy   7       alleg

我尝试使用总结和粘贴、变异和粘贴以及合并,但都没有成功。

df <- df %>%
  group_by(county) %>%
  summarise(allloc = paste(location))

df <- df %>%
  group_by(county) %>%
  mutate(allloc = paste(location))

df <- df %>%
  group_by(county) %>%
  mutate(allloc = coalesce(df$location))

有什么想法吗?

(最后但同样重要的是,这里有一些可重现的代码):

df <- data.frame(location = c("hend", "alam", "alex", "alleg", "ann"), county = c("hender", "alam", "alam", "allegy", "hender"), x = c(2, 0 , 4, 6, 9), y = c(10, 5, 3, 1, 0))

您可以在 summarise 中创建多个列:

library(dplyr)

result <- df %>%
           group_by(county) %>%
           summarise(total = sum(x + y), 
                     allloc = toString(location))
                     #Same as :
                     #allloc = paste0(location, collapse = ','))
result

#  county total allloc    
#  <chr>  <dbl> <chr>     
#1 alam      12 alam, alex
#2 allegy     7 alleg     
#3 hender    21 hend, ann 

虽然 toString 适合汇总信息,但如果您需要重新提取不同的位置,我觉得它更好(好吧,更多 general)将数据存储为列表列而不是字符串。 (后者需要重新解析它们以拆分它们,使用 strsplit 可以很简单,直到在实际数据中嵌入逗号或标记拆分器。)

results <- df %>%
  group_by(county) %>%
  summarise(total = sum(x + y), allloc = list(location) )
results
# # A tibble: 3 x 3
#   county total allloc   
#   <chr>  <int> <list>   
# 1 alam      12 <chr [2]>
# 2 allegy     7 <chr [1]>
# 3 hender    21 <chr [2]>

您可以通过 str 稍微了解引擎盖下发生的事情:

str(results)
# tibble [3 x 3] (S3: tbl_df/tbl/data.frame)
#  $ county: chr [1:3] "alam" "allegy" "hender"
#  $ total : int [1:3] 12 7 21
#  $ allloc:List of 3
#   ..$ : chr [1:2] "alam" "alex"
#   ..$ : chr "alleg"
#   ..$ : chr [1:2] "hend" "ann"

显示 allloc 正在显示一个列表,长度为 3,包含可变的字符串列表。

这将是 useful/justified 的时间:

  • 您对 location 数据进行了后续处理,希望将其保存在一定长度的向量中(对于每个 county);
  • 你会想要reconstitute/lengthen数据,这实际上只是上一个项目符号的特例;

不需要的次数:

  • 当您创建 allloc 的原因纯粹是为了可视化报告时;
  • 原始数据从未嵌入逗号。