Home > Software design >  Subsetting nested list in r: select first 3 elements from each and bind as df with cols to different
Subsetting nested list in r: select first 3 elements from each and bind as df with cols to different

Time:01-10

  1. In a nested list (list of lists), select the first three elements from each list (alternative: select by name (eg: c("hm", "ht", "cpht"))

  2. combine each list into a df with cols to differentiate them (see end result)


Example data:

df1 <- data.frame(
  gene = c("a", "b", "c"),
  mutation = c("x", "y", "z"))

list1 <- list(
  hm = df1,
  ht = df1,
  cpht = df1,
  panel = df1)

list_o_lists <- list(
  pt1 = list1,
  pt2 = list1,
  pt3 = list1)

Expected result 1:

list_desired <- list(
  hm = df1,
  ht = df1,
  cpht = df1)

list_o_lists_desired <- list(
  pt1 = list_desired,
  pt2 = list_desired,
  pt3 = list_desired)

Solution for 2: (NB: found the solution while typing the example data)

lol_final <- map(list_o_lists_desired, bind_rows, .id = "type")
df_final <- bind_rows(lol_final, .id = "pt")

CodePudding user response:

Solution 1:

lapply(list_o_lists, `[`, 1:3)
##> $pt1
##> $pt1$hm
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z
##> 
##> $pt1$ht
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z
##> 
##> $pt1$cpht
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z
##> 
##> 
##> $pt2
##> $pt2$hm
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z
##> 
##> $pt2$ht
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z
##> 
##> $pt2$cpht
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z
##> 
##> 
##> $pt3
##> $pt3$hm
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z
##> 
##> $pt3$ht
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z
##> 
##> $pt3$cpht
##>   gene mutation
##> 1    a        x
##> 2    b        y
##> 3    c        z

CodePudding user response:

alternative: selection by name:

lapply(list_o_lists, `[`, c("hm", "ht", "cpht")

Thanks a lot Stefano! (guess my R got a bit rusty during a clinical year in the ICU)

  • Related