0

I have two dataframe df1

structure(list(d.x = structure(c(1L, 2L, 3L, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), .Label = c("Sample1", 
"Sample2", "Sample3"), class = "factor"), d.Name = structure(c(1L, 
2L, 3L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA), .Label = c("A", "B", "C"), class = "factor")), .Names = c("d.x", 
"d.Name"), row.names = c(NA, -37L), class = "data.frame")

df2

structure(list(d.ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("Sample1", 
"Sample2", "Sample3"), class = "factor")), .Names = "d.ID", row.names =c(NA, 
-37L), class = "data.frame")

I want to replace all the name in df2 with corresponding name of df1 file so for examples Sample1 will be named as A

Sotos
  • 51,121
  • 6
  • 32
  • 66
KMISH
  • 49
  • 1
  • 8

1 Answers1

1

You can use match() as follows:

df2$d.Id.New <- df1$d.Name[match(df2$d.ID, df1$d.x)]

This creates a new column in df2 which will contain the matched value from df1:

> head(df2)
     d.ID d.Id.New
1 Sample1        A
2 Sample1        A
3 Sample1        A
4 Sample1        A
5 Sample1        A
6 Sample1        A
Stuart Allen
  • 1,537
  • 1
  • 10
  • 19