索引匹配并将匹配的值分配给变量

Index-Matching and assigning the matched value to a variable

我是 R 的新手,我想通过 R 执行一些简单的索引。

我有一个数据框,第一列是名称,第二列是相应的唯一 ID。我想为特定变量分配一个特定的 ID,并将其用于数据分析。例如:

names <- c('Kyle','Sophie','John','Peter','Julie','Carol')
IDs <- c('23513','15315','62352','25346','73424','03029')
df <- data.frame(names, IDs)

我有一个这样的数据框,想为一个变量分配一个特定的 ID,例如:

Student_ID <- (sample formula to bring in an ID using a name, say "Kyle" and this formula
brings in '23513')

我对编码环境非常陌生,所以我什至不知道这是否可行。

谢谢!

我们可以使用match获取names列数据中student_name的索引,并取回对应的ID。

student_name <- "Kyle"
Student_ID <- df$IDs[match(student_name, df$names)]
Student_ID

#[1] 23513
#Levels: 03029 15315 23513 25346 62352 73424