将数据框转换为列表 [英] Convert data frame to list
问题描述
我正在尝试从数据框到 R 中的列表结构(我知道从技术上讲数据框是一个列表).我有一个包含参考化学品及其机制不同目标的数据框.例如,雌激素是一种雌激素受体激动剂.我想要的是将数据框转换为列表,因为我厌倦了键入以下内容:
I am trying to go from a data frame to a list structure in R (and I know technically a data frame is a list). I have a data frame containing reference chemicals and their mechanisms different targets. For example, estrogen is an estrogen receptor agonist. What I would like is to transform the data frame to a list, because I am tired of typing out something like:
refchem$chemical_id[refchem$target=="AR" & refchem$mechanism=="Agonist"]
每次我需要访问特定参考化学品的列表时.我更愿意通过以下方式获取化学品:
every time I need to access the list of specific reference chemicals. I would much rather access the chemicals by:
refchem$AR$Agonist
我正在寻找一个通用的答案,尽管我给出了一个简化的例子,因为并非所有的目标都有所有的机制.
I am looking for a general answer, even though I have given a simplified example, because not all targets have all mechanisms.
这很容易用循环来完成:
This is really easy to accomplish with a loop:
example <- data.frame(target=rep(c("t1","t2","t3"),each=20),
mechan=rep(c("m1","m2"),each=10,3),
chems=paste0("chem",1:60))
oneoption <- list()
for(target in unique(example$target)){
oneoption[[target]] <- list()
for(mech in unique(example$mechan)){
oneoption[[target]][[mech]] <- as.character(example$chems[ example$target==target & example$mechan==mech ])
}
}
我只是想知道是否有更聪明的方法来做到这一点.我尝试使用 lapply
并没有取得任何进展.
I am just wondering if there is a more clever way to do it. I tried playing around with lapply
and did not make any progress.
推荐答案
使用split
:
split(refchem, list(refchem$target, refchem$mechanism))
应该可以.
新的访问方式是 refchem$AR.Agonist
这篇关于将数据框转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!