0

Im trying to find out if there is a way in R to compare the values of one column in a data frame (x) to the values in the first column of a second data frame (y). And if they match export that matching value in column 2 of y to a new data frame (z). The catch is that y has more rows than x. I tried to run y$X2[x$X1 == y$X1] and z$X1 <- ifelse(x$X1 == y$X1, y$X2, ifelse(x$X1 != y$X1, '')) but run into the error of "longer object length is not a multiple of shorter object length".

Examples of data frames x and y

x <- data.frame("X1" = c(2,33,45,67,32,5) 

y <- data.frame("X1" = c(2,33,37,45,60,79,67,32,5,15), "X2" = c(A,B,C,D,E,F,G,H,I,J)) 

So what Im looking for is z$X1 = A,B,D,G,H,I

Any help would be great and thank you

Sotos
  • 51,121
  • 6
  • 32
  • 66
Robert S
  • 49
  • 5

1 Answers1

1

You may try

z <- data.frame(
  X1 = y$X2[na.omit(match(x$X1, y$X1))]
)
z

  X1
1  A
2  B
3  D
4  G
5  H
6  I
Park
  • 14,771
  • 6
  • 10
  • 29