删除嵌套在列表中的不匹配数据框名称

问题描述 投票:0回答:2

我有两个由数据帧组成的列表--df_quintile和disease_df_quintile。我不知道如何简洁地表达它们,但这就是它们在Rstudio中的样子:

enter image description here

enter image description here

注意,disease_df_quintile由5个数据帧(数据帧1到5)组成,而疾病_df_quintile由4个(数据帧2到5)组成。我想交叉检查两个列表并删除两个列表都不共享的任何数据帧 - 所以在这种情况下,我想从df_quintile列表中删除第一个数据帧。我怎样才能做到这一点?

谢谢。

r
2个回答
1
投票

独立于列表的内容,您可以首先找到重复的名称,然后对列表进行子集化:

##-- Fake lists
l1 <- as.list(1:5)
names(l1) <- 1:5

l2 <- as.list(2:5)
names(l2) <- 2:5

##-- Common names and subsetting
common_names <- intersect(names(l1), names(l2))
l1 <- l1[common_names]
l2 <- l2[common_names]

1
投票

您可以匹配列表的名称并保留常用名称。

keep <- match(names(disease_df_quintile), names(df_quintile))
new_df_quintile <- df_quintile[keep]
© www.soinside.com 2019 - 2024. All rights reserved.