Fastest way to populate a column from another table in R?
I have 2 tables and I need to create a new column "Number" where it populates it with the col2 respective value. My data contains couple of hundreds of rows and I used for loop to populate it but it takes lots of time is there a faster way?
Col1 | Col2 |
---|---|
A | 55 |
B | 77 |
C | 80 |
D | 9 |
Letter | Number |
---|---|
A | |
B | |
C | |
D |
Solution 1:
Using match
.
transform(df2, Number=df1[match(Letter, df1$Col1), ]$Col2)
# Letter Number
# 1 A 55
# 2 B 77
# 3 C 80
# 4 D 9
Data:
df1 <- structure(list(Col1 = c("A", "B", "C", "D"), Col2 = c(55L, 77L,
80L, 9L)), class = "data.frame", row.names = c(NA, -4L))
df2 <- structure(list(Letter = c("A", "B", "C", "D"), Number = c(NA,
NA, NA, NA)), class = "data.frame", row.names = c(NA, -4L))