R 如何将分组后的数据帧转换为向量列表
我有以下数据框:R 如何将分组后的数据帧转换为向量列表,r,list,dataframe,dplyr,R,List,Dataframe,Dplyr,我有以下数据框: 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", "H
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"))
我该怎么做呢?您可以试试:
x = aggregate(motif~sample,df,c,simplify=FALSE)
y=x$motif
names(y) = x$sample
或者正如索托斯所指出的,最后两行可以替换为一行集合名(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"
希望这有帮助
split(df,df$sample)
?@RonakShah您的方法给出的是tibble列表,而不是向量列表。dd实际上,这应该是可行的<代码>拆分(df$motif,df$sample)
非常简单的解决方案,niceNo。我需要一个向量列表。仔细看我的专栏。我本来打算发表一篇非常类似的文章。在第二步中,您可以简单地使用设置名称
,并将其作为一步,即设置名称(x$motif,x$sample)
我知道必须有更好的方法来完成这一步。。。但是我找不到它。谢谢分享!
x = aggregate(motif~sample,df,c,simplify=FALSE)
y=x$motif
names(y) = 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"