r - 当按多个列分组时,如何在 dplyr 中命名 group_split 的列表

标签 r dplyr

我在 dplyr 中使用 group_split 并且在我拆分了不止一列之后我正在努力命名列表。

当我们按一列分组时,我知道如何做到这一点 here但我不知道在按两列拆分时如何执行此操作

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

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>  
.
.
.

关于r - 当按多个列分组时,如何在 dplyr 中命名 group_split 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57275613/

相关文章:

r - 方程组。如何拆分字符串以在 R 中获得两个矩阵 A 和 b

r - 同时对多列使用 dplyr 进行条件变异

r - 根据 data.frame 列值 R 分配点颜色

r - 我可以在 R 中使用向量作为正则表达式模式参数吗?

r - 嵌套列表中的唯一类

r - 划分两个 difftime 对象

r - 如何使用 dplyr 按因子操作 data.frame

重复具有特定值的行

r - 无论如何,有没有办法一起使用 dplyr 的滞后和超前函数

r - 将列值转换为 R 中的日期