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)