2015-11-05 53 views
1

我有一個向量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 

我想要做的是從指數轉列過程中的值從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,我該如何編寫代碼?

+2

'as.numeric(因子(招生$當然,水平=課程))'或'比賽(報名$當然,課程)'這IHA更清晰的意圖我,但我會認爲效率較低 – user20650

+1

@ user20650 - 發佈'em up! 'fastmatch :: fmatch'也可以用於更快的匹配 –

+0

乾杯,理查德 – user20650

回答

1

一對夫婦的接近

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

其中levels參數確保值是有序如預期

match(enrollment$course, courses) 

返回內courses

每個 enrollment$course的索引位置

而對於一個更快的比賽 - 從RichardScriven

fastmatch::fmatch(enrollment$course, courses) 
相關問題