Merge dataframes in R with different size and condition

Viewed 70

I'm trying to combine 2 csv files into one file. They have common id with different size. I used merge() but I got replicated data. I have the following data-frames;

SR <- c("SR1", "SR2", "SR2", "SR2", "SR3", "SR4", "SR4")
school <- c("S-1", "S-1", "S-2", "S-4", "S-2", "S-1", "S-5")
Y <- c(3,4,1,2,5,2,3)
data1 <- data.frame(SR.id, school, Y)


SR <- c("SR1", "SR1", "SR1", "SR2", "SR2", "SR2", "SR2", "SR2", "SR2", "SR2", "SR3", "SR3", "SR4", "SR4", "SR4")
class <- c("S-1.02", "S-1.05", "S-1.07", "S-1.01", "S-1.02", "S-1.03", "S-1.06", "S-2.03", "S-2.15", "S-4.02", "S-2.01", "S-2.03", "S-1.05", "S-1.06", "S-5.01")
data2 <- data.frame(SR, class)
data1
  SR     school     Y
  SR1     S-1       3
  SR2     S-1       4
  SR2     S-2       1
  SR2     S-4       2
  SR3     S-2       5
  SR4     S-1       2
  SR4     S-5       3

data2
  SR      class
  SR1     S-1.02 
  SR1     S-1.05
  SR1     S-1.07
  SR2     S-1.01
  SR2     S-1.02
  SR2     S-1.03
  SR2     S-1.06
  SR2     S-2.03
  SR2     S-2.15
  SR2     S-4.02
  SR3     S-2.01
  SR3     S-2.03
  SR4     S-1.05
  SR4     C-1.06
  SR4     C-5.01

where school is the result should be as

  SR      school     class      Y
  SR1      S-1       S-1.02     3
  SR1      S-1       S-1.05     3
  SR1      S-1       S-1.07     3
  SR2      S-1       S-1.01     4
  SR2      S-1       S-1.02     4
  SR2      S-1       S-1.03     4
  SR2      S-1       S-1.06     4
  SR2      S-2       S-2.03     1
  SR2      S-2       S-2.15     1
  SR2      S-4       S-4.02     2
  SR3      S-2       S-2.01     5
  SR3      S-2       S-2.03     5
  SR4      S-1       S-1.05     2
  SR4      S-1       S-1.06     2
  SR4      S-5       S-5.01     3

Thank you for your help.

2 Answers

An option is regex_left_join from fuzzyjoin

library(fuzzyjoin)
library(dplyr)
regex_left_join(data2, data1, by = c("SR", "class" = "school")) %>%
      select(SR = SR.x, school, class, Y)

#    SR    school   class    Y
# 1  SR1    S-1     S-1.2    3
# 2  SR1    S-1     S-1.5    3
# 3  SR1    S-1     S-1.7    3
# 4  SR2    S-1     S-1.1    4
# 5  SR2    S-1     S-1.2    4
# 6  SR2    S-1     S-1.3    4
# 7  SR2    S-1     S-1.6    4
# 8  SR2    S-2     S-2.3    1
# 9  SR2    S-2     S-2.9    1
# 10 SR2    S-4     S-4.2    2
# 11 SR3    S-2     S-2.1    5
# 12 SR3    S-2     S-2.3    5
# 13 SR4    S-1     S-1.5    2
# 14 SR4    S-1     S-1.6    2
# 15 SR4    S-5     S-5.1    3

Could you edit your problem and use dput to put your two df's into a form that would be easier for us to grab?

Having said that, you need to do something like

# NOT RUN
library(tidyverse)
RESULT <- data2 %>%
  mutate(comparison.id = str_detect(outcome.id, "^.+\\d+")) %>%
  inner_join(data1, by = c("SR.id", "comparison.id"))
Related