0

I am trying to crate and append a new variable to a data set whose values will come from matching variable value of another data set.

For example

    data set 1
        A B
        1 a
        2 b
        3 c
    data set 2
        A 
        1
        2
        3
        1
        3
        2

And I want my result to look like

data set 2
    A B
    1 a
    2 b
    3 c
    1 a
    3 c
    2 b

I tried to use below "Match" function to obtain the result

data set 2$B <- data set 1$B[match(data set 1$A, data set 2$A)]

But it was throwing an error that there are

incorrect number of dimensions

How to deal with this? Please note that i don't want to merge both data sets because data set 2 contains hundreds or other variables.

The question was put to deal with the dimension error too.

Thanks, Mrinal

data9
  • 77
  • 1
  • 7

1 Answers1

0

Your data:

df1 <- data.frame(A=1:3,B=letters[1:3])
df2 <- data.frame(A= c(1:3, c(1,3,2)))

Using match:

df2$B <- df1$B[match(df2$A,df1$A)]
df2

  A B
1 1 a
2 2 b
3 3 c
4 1 a
5 3 c
6 2 b
CPak
  • 13,260
  • 3
  • 30
  • 48
  • Thanks you after changing the sequence of match variables in match function, it worked lick a charm. – data9 Jun 18 '17 at 16:57