rdata-manipulation

How to create a table using two other tables?


I have two tables. One is called enrollment, the other is called students.

enrollment

student_id   class_id  
004           compsci
010           compsci
002            engli
010            engli
003            engli

students:

student_id    first_name
  002           Abril
  004           Chris
  010           Davis
  003           Riley

I need an output table like below where only the class_id and first_name appears by a match of student_id and first_name from the above two tables.

class_id   first_name   
compsci      Davis
compsci      Chris
engli        Abril
engli        Davis
engli        Riley           
 

Data:

enrollment<-data.frame(student_id=(c(004,010,002,010,003)),class_id=(c("compsci","compsci","engli","engli","engli")))
student<-data.frame(student.id=c(002,004,010,003),first_name=(c("Abril","Chris","Davis","Riley")))

     
 

Solution

  • With dplyr:

    library(dplyr)
    #Code
    new <- student %>% left_join(enrollment,by = c('student.id'='student_id')) %>% select(-student.id)
    

    Output:

      first_name class_id
    1      Abril    engli
    2      Chris  compsci
    3      Davis  compsci
    4      Davis    engli
    5      Riley    engli