mr_swap
mr_swap

Reputation: 341

find intersect by rows in r

I am trying to find common targets affected by drugs (shown as entry number in following table).

IDARUBICIN <- c(1,5,12,13,18,27,NA,NA,NA,NA,NA,NA)
EPIRUBICIN <- c(1,2,5,6,12,13,17,18,19,21,23,24)
DAUNORUBICIN <- c(1,4,5,11,12,13,16,18,19,27,41,44)
VINBLASTINE <- c(1,4,5,12,13,18,19,27,30,37,39,44)
VINORELBINE <- c(1,5,12,13,18,19,27,41,44,NA,NA,NA)
all <- rbind(IDARUBICIN,EPIRUBICIN,DAUNORUBICIN,VINBLASTINE,VINORELBINE)
> all
             [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
IDARUBICIN      1    5   12   13   18   27   NA   NA   NA    NA    NA    NA
EPIRUBICIN      1    2    5    6   12   13   17   18   19    21    23    24
DAUNORUBICIN    1    4    5   11   12   13   16   18   19    27    41    44
VINBLASTINE     1    4    5   12   13   18   19   27   30    37    39    44
VINORELBINE     1    5   12   13   18   19   27   41   44    NA    NA    NA

I tried finding intersect using each row that worked fine

ans <- Reduce(intersect, list(all[1,],all[2,],all[3,],all[4,],all[5,]))
> ans
[1]  1  5 12 13 18

But I have 30 rows (i.e. 30 drugs) so I can't use this method. Can someone please tell me how to find intersect of a table by rows? I can't use my above mentioned solution, because it requires me to type each row and I don't want to do that

Upvotes: 0

Views: 190

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145755

Reduce(intersect, data.frame(t(all)))
# [1]  1  5 12 13 18

No extra dependencies needed!

Upvotes: 4

amarchin
amarchin

Reputation: 2114

library(tibble)
library(purrr)

t(all) %>% 
  as_tibble() %>% 
  reduce(intersect)

Upvotes: 1

Related Questions