user5249203
user5249203

Reputation: 4648

R- accessing list of list from a dataframe

I have a data frame (below) generated from
{ a<-as.data.frame(entrez_db_searchable(db = "pubmed", config = NULL)) }

  Name          FullName        
1  ALL          All Fields        
2  UID          UID        
3 FILT          Filter        
4 TITL          Title        
5 WORD          Text Word        
6 MESH          MESH Terms

MeSH Terms

I would like to access all the elements in a$FullName. The result looks like list of list.

$ALL 
[1] "All Fields"
$UID
 [1] "UID"
 $FILT
 [1] "Filter"

and so on...

I am trying to and was unsuccessful to access the expanded terms in the list in the following format a <- some_simple_function(df$FullName) print (a) output of the expanded terms stored in 1x1 column ( each row for each term).

Full Name
1  All Fields
2  UID
3  Filter
4  Title
5  MeSH Terms 

and so on.....

I appreciate if anyone can help me out. Note: I tried the following 1) for loop. ( prefer to see if there is a better way than for loop) 2) do.call("paste", c(a$FullName, sep = "\n"))paste does not recognize new line "\n" argument. 3) cat(do.call("paste", c(a$FullName, sep = "\n"))) , prints out the exact output I am looking for, but it is a print statement. I need to store the output in another variable.

Upvotes: 0

Views: 2072

Answers (2)

Nick
Nick

Reputation: 437

https://purrr.tidyverse.org/reference/flatten.html

flatten() is a tidy way of doing unlist()

This should work:

a %>%
  transmute(
  FullName = flatten_chr(FullName)
  )

Upvotes: 0

josliber
josliber

Reputation: 44320

I wasn't quite able to get your example data frame working, but this worked for me:

library(rentrez)
a<-as.data.frame(entrez_db_searchable(db = "pmc", config = NULL))

To deal with the fact that a$FullName is returning a list of 1-element vectors, you can use unlist to grab a vector of the names:

data.frame(FullName=unlist(a[,"FullName"]))
#                         FullName
# ALL                   All Fields
# UID                          UID
# FILT                      Filter
# PMID                   PubMed ID
# AUTH                      Author
# ...

Upvotes: 1

Related Questions