0

Hello I have 2 data frames:

d <- data.frame(v1 = c("A","B","C","D","E","F","G","H"), 
                v2 = c(1,2,3,4,5,6,7,8),
                v3 = c(1,2,3,4,5,6,7,8))                )

m<-data.frame(v4 = c("B","H","A","C","D"))

I want to change the m in a way that m$v4 it will match the d$v1 and also create an m$v5 with the relative data of d$v2 and an m$v6 with the relative data of d$v3 based on the matching.

My final m data frame should look like this:

 m
  v4 v5 v6
1  B  2  2
2  H  8  8
3  A  1  1
4  C  3  3
5  D  4  4
firmo23
  • 7,490
  • 2
  • 38
  • 114

2 Answers2

2

Plenty of ways to do this:

  1. Using dplyr::left_join:

    dplyr::left_join(m, d, by = c("v3" = "v1"))
    #  v3 v2
    #1  B  2
    #2  H  8
    #3  A  1
    #4  C  3
    #5  D  4
    
  2. Using merge:

    merge(m, d, by.x = "v3", by.y = "v1", sort = F)
    #  v3 v2
    #1  B  2
    #2  H  8
    #3  A  1
    #4  C  3
    #5  D  4
    

Update

Similar with your revised sample data

merge(m, d, by.x = "v4", by.y = "v1", sort = F)
#  v4 v2 v3
#1  B  2  2
#2  H  8  8
#3  A  1  1
#4  C  3  3
#5  D  4  4
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

We can use match from base R

m$v4 <- d$v2[match(m$v3, d$v1)]

Update

If we have multiple columns, then loop through the columns of interest and do the match

m[paste0("v", 5:6)] <- lapply(d[-1], function(x) x[match(m$v4, d$v1)])
m
#   v4 v5 v6
#1  B  2  2
#2  H  8  8
#3  A  1  1
#4  C  3  3
#5  D  4  4
akrun
  • 874,273
  • 37
  • 540
  • 662