Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何根据向量的索引转换列中的值?_R_Apply - Fatal编程技术网

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

R 如何根据向量的索引转换列中的值?,r,apply,R,Apply,我有一个向量课程: courses <- c("Math","English","Sport","Physik", "Chemie") # > courses [1] "Math" "English" "Sport" "Physik" "Chemie" 我要做的是将列course中的值从注册转换为课程索引中的课程id: > enrollment couse_id 1 3 2 4 3 3 4 2 5

我有一个向量
课程

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

# > courses
[1] "Math"    "English" "Sport"   "Physik"  "Chemie" 
我要做的是将列course中的值从
注册
转换为
课程
索引中的课程id:

> enrollment
  couse_id
1        3
2        4
3        3
4        2
5        2
6        1
7        5
8        1
我怎样才能有效地做到这一点

如果我想使用
which()
获取课程索引,并使用
apply()
将其应用于
注册
,我如何编写代码?

有几种方法

as.numeric(factor(enrollment$course, levels=courses)) 
其中
levels
参数确保值按预期顺序排列

返回
课程中每个
注册$course
的索引位置

为了更快的比赛-来自理查德斯克里文

fastmatch::fmatch(enrollment$course, courses)

as.numeric(因子(注册$course,levels=courses))
match(注册$course,courses)
这对我来说是一个更清晰的意图,但我想得更少efficient@user20650-贴上去<代码>快速匹配::fmatch
也可用于更快的匹配
match(enrollment$course, courses)
fastmatch::fmatch(enrollment$course, courses)