如何根据向量的索引转换列中的值?

How can I transform the the values from a column according to the index of a vector?

我有一个向量 courses:

courses <- c("Math","English","Sport","Physik", "Chemie")

# > courses
[1] "Math"    "English" "Sport"   "Physik"  "Chemie" 

我有一个数据框enrollment:

enrollment <- data.frame(course=c("Sport", "Physik", "Sport", "English", "English", "Math", "Chemie", "Math"))

> enrollment
   course
1   Sport
2  Physik
3   Sport
4 English
5 English
6    Math
7  Chemie
8    Math

我想要做的是将列 course 中的值从 enrollment 转换为 course_id 从 course:

的索引
> enrollment
  couse_id
1        3
2        4
3        3
4        2
5        2
6        1
7        5
8        1

我怎样才能有效地做到这一点?

如果我想使用which()获取课程索引并使用apply()应用到enrollment,我该如何编写代码?

几种方法

as.numeric(factor(enrollment$course, levels=courses)) 

其中 levels 参数确保值按预期排序

match(enrollment$course, courses)

其中 returns enrollment$coursecourses

中的索引位置

为了更快的匹配 - 来自 RichardScriven

fastmatch::fmatch(enrollment$course, courses)