-3

I am new to R. I have 3 data frames as

a1
1 p53
2 NFKB
3 P73
4 P21
5 PTEN

a2
1 p21
2 p53
3 ERGIC3
4 MAP3K3
5 PTEN

a3
1 PTEN
2 MAP3K3
3 ERGIC3
4 AURKA
5 p53

I have get a table as the output showing only the common values like p53 and PTEN which is common in all the three data frames. How should I write the code in R?

jose_bacoy
  • 12,227
  • 1
  • 20
  • 38
  • I'm not sure if this is what you want, since you haven't provided a reporoducible example, but maybe you want something like `df1[, intersect(names(df1), names(df2), names(df3))]` – IceCreamToucan Mar 14 '18 at 20:48
  • 5
    Please read https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and https://stackoverflow.com/tour. – ngm Mar 14 '18 at 20:49

1 Answers1

3

You can use Reduce and intersect in a one-liner.

I assume a1, a2, a3 are really data.frames (and not vectors). Then do:

common_elements <- Reduce(intersect, list(a1[, 1], a2[, 1], a3[, 1]));
common_elements;
#[1] "p53"  "PTEN"

If instead a1, a2, a3 were vectors, you'd do

common_elements <- Reduce(intersect, list(a1, a2, a3));
common_elements;

Sample data

a1 <- read.table(text =
    "a1
1 p53
2 NFKB
3 P73
4 P21
5 PTEN", header = T)

a2 <- read.table(text = 
    "a2
1 p21
2 p53
3 ERGIC3
4 MAP3K3
5 PTEN", header = T)

a3 <- read.table(text = 
    "a3
1 PTEN
2 MAP3K3
3 ERGIC3
4 AURKA
5 p53", header = T)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68