当按多个列分组时,如何在dplyr中命名group_split的列表 [英] How to name a list of a group_split in dplyr when grouped by more than one column

查看:208
本文介绍了当按多个列分组时,如何在dplyr中命名group_split的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在dplyr中使用了group_split,在我被多个列拆分后,我正在努力命名列表。

I am using group_split in dplyr and I am struggling to name the list after I have split by more than one column.

我知道当我们执行此操作时按一列分组此处但我不确定将其分为两列时如何做

I know how to do this when we group by one column here but I am not sure how to do this when splitting by two columns

我无法共享数据,但是如果使用虹膜数据集,它将类似于此(在我的情况下,两列都是因素)

I can't share the data but if using the iris dataset, it would be similar to this (in my case both columns are factors)

iris %>%
group_split(Species, Petal.Width)


推荐答案

使用 dplyr :: group_keys ()获取分组变量。

library(dplyr)
library(stringr)
# make grouped data frame
iris_group <- iris %>%
    group_by(Species, Petal.Width)

# get group keys
group_name_df <- group_keys(iris_group) %>%
    mutate(group_name = str_c(as.character(Species),"-",Petal.Width))

# get name for each group
group_name <- group_name_df$group_name

# assign name to each split table
df_list <- group_split(iris_group) %>%
    setNames(group_name)



> group_name_df
# A tibble: 27 x 3
   Species    Petal.Width group_name    
   <fct>            <dbl> <chr>         
 1 setosa             0.1 setosa-0.1    
 2 setosa             0.2 setosa-0.2    
 3 setosa             0.3 setosa-0.3    
 4 setosa             0.4 setosa-0.4    
 5 setosa             0.5 setosa-0.5    
 6 setosa             0.6 setosa-0.6    
 7 versicolor         1   versicolor-1  
 8 versicolor         1.1 versicolor-1.1
 9 versicolor         1.2 versicolor-1.2
10 versicolor         1.3 versicolor-1.3
# ... with 17 more rows



> df_list 
$`setosa-0.1`
# A tibble: 5 x 5
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
         <dbl>       <dbl>        <dbl>       <dbl> <fct>  
1          4.9         3.1          1.5         0.1 setosa 
2          4.8         3            1.4         0.1 setosa 
3          4.3         3            1.1         0.1 setosa 
4          5.2         4.1          1.5         0.1 setosa 
5          4.9         3.6          1.4         0.1 setosa 

$`setosa-0.2`
# A tibble: 29 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>  
.
.
.

这篇关于当按多个列分组时,如何在dplyr中命名group_split的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆