You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中根据列名匹配值创建新变量grade的实现方法

Solution to Create the 'grade' Variable

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:22:09