Wendy
Wendy

Reputation: 144

Covert a multi level nested list with unequal length to a dataframe

I have a list like this (output of biclqiues()):

A<- list(
biclique1 = list(left = c("EVELYN", "LAURA", "BRENDA"), right = c("1", "3", "5", "6", "8")), 
biclique2 = list(left = c("EVELYN", "LAURA", "THERESA"), right = c("2", "3", "5", "6", "8")), 
biclique3 = list(left = c("EVELYN",  "LAURA",   "THERESA", "BRENDA",  "FRANCES"), right = c("3", "5", "6", "8")))

I need to further analyze the output. How can I make A into a data frame or some form that can be used for other operations?

For example, I want to look at all the clique members of "EVELYN", that would be -"EVELYN", "LAURA", "THERESA", "BRENDA", "FRANCES".

Can the left parts (names) and right parts (numbers) go into two dataframes?

Upvotes: 1

Views: 78

Answers (1)

Cole
Cole

Reputation: 11255

Here's a base solution. lapply loops through the three biclique elements and then extracts with [[ the left and right parts of the lists. stack simplifies the lapply() result into a nice data.frame:

left_df <- stack(lapply(A, `[[`, 'left'))
left_df

#    values       ind
#1   EVELYN biclique1
#2    LAURA biclique1
#3   BRENDA biclique1
#4   EVELYN biclique2
#5    LAURA biclique2
#6  THERESA biclique2
#7   EVELYN biclique3
#8    LAURA biclique3
#9  THERESA biclique3
#10  BRENDA biclique3
#11 FRANCES biclique3

left_df[left_df$values == 'EVELYN', ]

#  values       ind
#1 EVELYN biclique1
#4 EVELYN biclique2
#7 EVELYN biclique3

# and your direct question - this is base but there are simpler answers in dplyr and data.table:
unique(left_df[left_df$ind %in% left_df[left_df$values == 'EVELYN', 'ind'], 'values'])

#"EVELYN"  "LAURA"   "BRENDA"  "THERESA" "FRANCES"

Right branch:

right_df <- stack(lapply(A, `[[`, 'right'))
right_df

#   values       ind
#1       1 biclique1
#2       3 biclique1
#3       5 biclique1
#4       6 biclique1
#5       8 biclique1
#6       2 biclique2
#7       3 biclique2
#8       5 biclique2
#9       6 biclique2
#10      8 biclique2
#11      3 biclique3
#12      5 biclique3
#13      6 biclique3
#14      8 biclique3

Upvotes: 1

Related Questions