1

I have dataframe

df1 ->

ID Name
1  Test1
2  Test2
3  Test3

I have another dataframe df2

df2 ->

ID Name
1  Char
2  Float
3  Decimal
4  String

Now I want to update df1 name values based on names from df2 using ID

Now my df1 output should be

ID Name
1  Char
2  Float
3  Decimal 

Please let me know how to acheive this.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Vinoth
  • 29
  • 1
  • 7
  • 1
    I would try to be clearer about whether you want to do a lookup by ID, or just match identically numbered rows. – Jack Wasey Nov 17 '15 at 02:13

4 Answers4

4

We can use match

df1$Name <- df2$Name[match(df1$ID, df2$ID)]

Or as @thelatemail mentioned, this can be solved with merge

merge(df1["ID"], df2, all.x=TRUE)
thelatemail
  • 91,185
  • 12
  • 128
  • 188
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Another option:

library(qdapTools)
df1$Name <- df1$ID %l% df2
Steven Beaupré
  • 21,343
  • 7
  • 57
  • 77
0

Not sure if you were looking for something besides simply this:

df1$Name <- df2$Name[1:3]
Adam Birenbaum
  • 940
  • 9
  • 23
0

Use the ID to get the right names.

df1$Name <- df2$Name[df1$ID]

Note that this solution is applicable if the number of observations in df1 is less than or equals to the number of observations in df2, otherwise, you will end up with NA. Also, the ID is the row number.

Fadwa
  • 1,717
  • 5
  • 26
  • 43