将数据框转换为列表 [英] Convert data frame to list

查看:1084
本文介绍了将数据框转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从R中的数据帧转到列表结构(而且我从技术上知道数据帧是一个列表)。我有一个包含参考化学品及其机制的数据框架不同的目标。例如,雌激素是雌激素受体激动剂。我想要的是将数据框转换为列表,因为我厌倦了输入如下的东西:

  refchem $ chemical_id [refchem $ target ==AR& refchem $ mechanism ==Agonist] 

每次我需要访问特定参考化学品列表。我更愿意通过以下方式访问化学品:

  refchem $ AR $ Agonist 
/ pre>

我正在寻找一个一般的答案,即使我给了一个简化的例子,因为并不是所有的目标都有所有机制。



这是一个非常容易的循环:

  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 [[目标]]< - list()
for(mech in unique(example $ mechan)){
oneoption [[target]] [[mech]]< - as.character(example $ chems [example $ target == target& example $ mechan == mech])
}
}

我只是想知道是否有更聪明的方法来做到这一点。我试过玩过 lapply ,没有任何进展。

解决方案

使用 split

  split(refchem,list(refchem $ target ,refchem $ mechanism))

应该做的伎俩。



新的访问方式将是 refchem $ AR.Agonist


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 ])
  }
}

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.

解决方案

Using split:

split(refchem, list(refchem$target, refchem$mechanism))

Should do the trick.

The new way to access would be refchem$AR.Agonist

这篇关于将数据框转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆