分组数据框列表

时间:2016-09-22 11:49:55

标签: r tidyverse

我有一个包含分组名称的数据框,如下所示:

<div class="chat_widget_body">
  <div class="chat_widget_bubble_green"> Too much headache since last night. Please guide me
    <div class="msg_time">Today | 11:00 am <i class="fa fa-check" aria-hidden="true"></i></div>
  </div>
  <div class="chat_widget_notification">Payment of Rs. 330.00 Received</div>
</div>
<div class="chat_widget_footer"></div>

我想将其转换为一个列在组名称上并包含名称的列表。示例输出:

df <- data.frame(group = rep(letters[1:2], each=2),
                 name = LETTERS[1:4])
> df
  group name
1     a    A
2     a    B
3     b    C
4     b    D

这是not a new question,但我想在整齐的范围内完成这项工作。

2 个答案:

答案 0 :(得分:9)

据我所知,在tidyverse中还没有这样的功能。因此,您必须自己编写:

split_tibble <- function(tibble, col = 'col') tibble %>% split(., .[,col])

然后:

dflist <- split_tibble(df, 'group')

导致数据帧的出现:

> dflist
$a
  group name
1     a    A
2     a    B

$b
  group name
3     b    C
4     b    D

> sapply(dflist, class)
           a            b 
"data.frame" "data.frame" 

要获得所需的输出,您必须稍微扩展一下这个功能:

split_tibble <- function(tibble, column = 'col') {
  tibble %>% split(., .[,column]) %>% lapply(., function(x) x[,setdiff(names(x),column)])
}

现在:

split_tibble(df, 'group')

结果:

$a
[1] A B
Levels: A B C D

$b
[1] C D
Levels: A B C D

考虑到评论和答案中的备选方案,得出以下结论:使用基础R替代split(df$name, df$group)更为明智。

答案 1 :(得分:1)

使用tidyverse

library(tidyr)
library(dplyr)
df$ID<-1:nrow(df)  #unique variable
lst<-df%>%spread(group,name)%>%select(-ID)%>%as.list()
lapply(lst,function(x)x[!is.na(x)]
相关问题