在R语言中根据列名匹配值创建新变量grade的实现方法
Absolutely! You can easily create the grade variable by pulling the test score specified in the select column for each row. Here are two practical approaches in R:
Base R Approach
Using row-column indexing, we can directly fetch the correct score from the column named in select:
# Original data frame students <- data.frame(name = c("student1", "student2", "student3", "student4"), test1 = c(50, 30, 20, 6), test2 = c(30, 20, 15, 10), select = c("test2", "test1", "test2", "test1")) # Add the grade variable students$grade <- students[cbind(seq(nrow(students)), match(students$select, colnames(students)))] # View the result students
This works because cbind(seq(nrow(students)), match(students$select, colnames(students))) creates a matrix of (row, column) pairs. For each row, we use the position of the select value in the column names to grab the corresponding test score.
Tidyverse (dplyr) Approach
If you prefer a more readable, pipe-based workflow:
library(dplyr) students <- students %>% rowwise() %>% mutate(grade = pull(cur_data(), select)) %>% ungroup() # Check the output students
rowwise() ensures we process each row individually, and pull(cur_data(), select) extracts the value from the column specified in the select column for that row.
Final Output
Both methods will produce your desired result:
> students name test1 test2 select grade 1 student1 50 30 test2 30 2 student2 30 20 test1 30 3 student3 20 15 test2 15 4 student4 6 10 test1 6
内容的提问来源于stack exchange,提问作者imprela

