r中的子集嵌套列表:从每个元素中选择前3个元素,并绑定为df,用cols区分它们


  1. 在嵌套列表(列表的列表)中,从每个列表中选择前三个元素(可选择:按名称选择(例如:c(" html ", " html ", "cpht"))

  2. 将每个列表合并成带有颜色的df以区分它们(参见最终结果)


示例数据:

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)

预期结果1:

list_desired <- list(
hm = df1,
ht = df1,
cpht = df1)
list_o_lists_desired <- list(
pt1 = list_desired,
pt2 = list_desired,
pt3 = list_desired)

解决方案2:(注意:在输入示例数据时找到了解决方案)

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

解决方案一:

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

alternative: selection by name:

lapply(list_o_lists, `[`, c("hm", "ht", "cpht")
非常感谢Stefano!(我猜我的R在ICU的临床一年里有点生锈了)

最新更新