将值匹配到列名以在R中创建新变量

时间:2018-05-11 20:09:20

标签: r

我有一个看起来像这样的数据集

    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"))

有没有办法创建一个名为&#39; grade&#39;这将包含&#39;选择&#39;中出现的任何变量的测试分数。

此处的示例输出:

    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"),
                   grade = c(30, 30, 15, 6))

2 个答案:

答案 0 :(得分:0)

以下是Base R解决方案:

students$value = with(students, ifelse(select == 'test1', test1, test2))

或来自case_when的{​​{1}}:

dplyr

此解决方案还扩展到library(dplyr) students %>% mutate(value = case_when( select == 'test1' ~ test1, TRUE ~ test2)) 测试。

<强>结果:

n

答案 1 :(得分:0)

如果你想在基础R中执行此操作,并且只有少量测试可供选择,则可以使用以下代码执行此操作:

students$Grade[students$select=="test1"] <- as.numeric(students$test1[students$select=="test1"])
students$Grade[students$select=="test2"] <- as.numeric(students$test2[students$select=="test2"])

结果:

      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