Getting the group match from two data frames keeping the row order in R

Viewed 62

I have these datasets:

data_a <- data.frame(label = c("A","B","C","D"))
data_b <- data.frame(lobel = c("C","D","B","A"),
                     parsu = c("TR","TR","TD","TD"))

And I want data_a to match the group parsu keeping the row order of data_a so the expected result is:

label   parsu
A       TD
B       TD
C       TR
D       TR

What I have tried is:

data_a %>% left_join(data_b, by = c("label","lobel"))

But I get this error message:

Error: Join columns must be present in data.
x Problem with `lobel`.

Please, could you help me with this question? What is the reason that I can't join those two data frames?

3 Answers

In order for your code to work you just have to put = between the column names you would like to match. Normally when the column names don't match we put an equal sign between the pair of names that are supposed to match.

library(dplyr)

data_a %>%
  left_join(data_b, by = c("label" = "lobel"))

  label parsu
1     A    TD
2     B    TD
3     C    TR
4     D    TR
data.frame(label=data_b$lobel[match(data_a$label,data_b$lobel)],parsu=data_b$parsu[match(data_a$label,data_b$lobel)])

This gives the desired data frame by reordering data_b via the match() function. Another way would be:

colnames(data_b)[1] <- "label"
data_b[match(data_a$label,data_b$label),]

We can use merge from base R

merge(data_a, data_b, all.x = TRUE, by.x = 'label', by.y = 'lobel')
Related