Workhorse
Workhorse

Reputation: 1560

Remove Non-Matching Dataframe Names Nested in A List

I have two lists consisting of dataframes - df_quintile and disease_df_quintile. I do not know how to represent them concisely, but this is how they look like in Rstudio:

enter image description here

enter image description here

Notice, disease_df_quintile consists of 5 dataframes (dataframes 1 through 5), while disease_df_quintile consists of 4 (dataframes 2 through 5). I would like to cross check both lists and remove any dataframes that are not shared by both lists - so in this case, I would like to remove the first dataframe from the df_quintile list. How can I achieve this?

Thank you.

Upvotes: 0

Views: 138

Answers (2)

Douglas Mesquita
Douglas Mesquita

Reputation: 1021

Independently of the content of the list, you can first find the repeated names and then subsetting the lists:

##-- 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]

Upvotes: 1

Rui Barradas
Rui Barradas

Reputation: 76585

You can match the list's names and keep the common ones.

keep <- match(names(disease_df_quintile), names(df_quintile))
new_df_quintile <- df_quintile[keep]

Upvotes: 1

Related Questions