我有以下数据框:
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"))
看起来像这样:
> 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
我想要做的是将其转换为向量列表,就像创建它一样:
list(`HMSC-ad`= c("AP-1", "BORIS"),
#.. etc ..
"HVMSC" = c("BATF", "CTCF"))
我该怎么做?
答案 0 :(得分:2)
你可以尝试:
x = aggregate(motif~sample,df,c,simplify=FALSE)
y=x$motif
names(y) = x$sample
或者Sotos指出,最后两行可以用单行setNames(x$motif, x$sample)
替换。
两者都导致:
$`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"
希望这有帮助!