How to figure out which patients appeared under both IDs in R?

Viewed 51

I have a list of patient IDs, but they go by two different IDs(ID1 and ID2). How do I figure out which patients on the list appeared under both IDs?

ID1 ID2
 11  12
 13  14
 15  16
 17  18
 19  20
 21  22

I have a list

list=c(11,13,14,15,16,18,18,19,20)

I need to see which patients appeared under both IDs, by ID1, such that I would get

>13,15,19

Thank you!

3 Answers

We could loop over the dataset with lapply, check whether the elements are %in% the 'list' object (not recommended to name objects with function names), Reduce it to a single logical vector with & (it implies TRUE only if both columns have the value in the 'list'). Use the logical index to subset the values of "ID1"

df1$ID1[Reduce(`&`, lapply(df1, `%in%`, list))]
#[1] 13 15 19

Or another option is filter with across from dplyr. It will filter only those rows having both column values are present and then pull the 'ID1' column

library(dplyr)
df1 %>% 
   filter(across(everything(), ~ . %in% list)) %>% 
   pull(ID1)
#[1] 13 15 19

data

df1 <- structure(list(ID1 = c(11L, 13L, 15L, 17L, 19L, 21L), ID2 = c(12L, 
 14L, 16L, 18L, 20L, 22L)), class = "data.frame", row.names = c(NA, 
 -6L))

Here is a base R option using match + complete.cases

> df$ID1[complete.cases(sapply(df, match, table = lst))]
[1] 13 15 19

Using sapply you could do :

df$ID1[rowSums(sapply(df, `%in%`, list)) == ncol(df)]
#[1] 13 15 19
Related