Warm tip: This article is reproduced from stackoverflow.com, please click
match r matching

how do i match multiple column from different dataset in R

发布于 2020-03-27 15:44:56

I need to fetch teacher name by matching the subject and board from studentdata and tutordata. Code--

Studentdata$Tutor.name <- Tutordata[cbind(
  match(Studentdata$Subject, Tutordata$TSubject),
  match(Studentdata$Board, colnames(Tutordata))
)]

Tutordata

Tname TSubject TBoard
A     Physics   IB, IGCSE
B     Physics   CBSE,JEE mains
C     Math      JEE mains
D     Math      IGCSE
E     Physics   ICSE

StudentData

StudentName Board   Subject
X          IB       Math
Arjun      IB       Physics 
Rehana     IGCSE    Physics 
Rashid     CBSE     Math    
Ashika     JEE mainsMath    
Aagya      ICSE     Math

All the variables are factors in the above dataset.

Questioner
Kiku Sekar
Viewed
16
Ronak Shah 2020-01-31 17:46

Probably, you can try to split TBoard column into separate rows and then do a join.

library(dplyr)

tidyr::separate_rows(Tutordata, TBoard, sep = ",") %>%
   mutate(TBoard = trimws(TBoard)) %>%
   right_join(StudentData, by = c('TBoard' = 'Board', 'TSubject' = 'Subject'))

However, there doesn't seem any matches in your data.