pdubois
pdubois

Reputation: 7800

How to convert data frame after group_by into list of vectors

I have the following data frame:

df <- structure(list(motif = c("AP-1", "BORIS", "AP-1", "RUNX", "AP-1", 
"Etv2", "AP-1", "CTCF", "AP-1", "TEAD", "BATF", "CTCF"), sample = c("HMSC-ad", 
"HMSC-ad", "HMSC-bm", "HMSC-bm", "HMSC-he", "HMSC-he", "HPMSC", 
"HPMSC", "HUMSC", "HUMSC", "HVMSC", "HVMSC")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -12L), .Names = c("motif", 
"sample"))

It looks like this:

 > library(tidyverse)
 > df %>% group_by(sample)
# A tibble: 12 x 2
# Groups:   sample [6]
   motif  sample
   <chr>   <chr>
 1  AP-1 HMSC-ad
 2 BORIS HMSC-ad
 3  AP-1 HMSC-bm
 4  RUNX HMSC-bm
 5  AP-1 HMSC-he
 6  Etv2 HMSC-he
 7  AP-1   HPMSC
 8  CTCF   HPMSC
 9  AP-1   HUMSC
10  TEAD   HUMSC
11  BATF   HVMSC
12  CTCF   HVMSC

What I want to do is to conver it into a list of vectors, as if it is created like:

list(`HMSC-ad`= c("AP-1", "BORIS"), 
      #.. etc ..
      "HVMSC" = c("BATF", "CTCF"))

How can I do that?

Upvotes: 1

Views: 35

Answers (1)

Florian
Florian

Reputation: 25435

You could try:

x = aggregate(motif~sample,df,c,simplify=FALSE)
y=x$motif
names(y) = x$sample

or as Sotos points out, the last two lines can be replaced with the one-liner setNames(x$motif, x$sample).

Both result in:

$`HMSC-ad`
[1] "AP-1"  "BORIS"

$`HMSC-bm`
[1] "AP-1" "RUNX"

$`HMSC-he`
[1] "AP-1" "Etv2"

$HPMSC
[1] "AP-1" "CTCF"

$HUMSC
[1] "AP-1" "TEAD"

$HVMSC
[1] "BATF" "CTCF"

Hope this helps!

Upvotes: 2

Related Questions