Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

r - Convert data frame to list

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using split:

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

Should do the trick.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...