我正在尝试自动创建变量来指示学生的答案(以l,m,f或g开头的变量)是否对问题(例如。以“test_”开头的变量)是否正确。即。例如,通过检查test_l1 == l1是否可以完成此操作。
除了使用索引之外,我不知道如何做到这一点,但它非常单调乏味,并创建了许多代码。
下面是一个模仿实际数据集结构的玩具数据集,它有4种不同的测试,每个测试有12个练习(test_l1 ~ test_l12,test_m1 ~ test_m12,test_f1~,test_g1~)和相应的学生回答(l1~l12,m1~m12,f1~,g1~)。我想创建48个变量,即correct_l1 ~ correct_l12、correct_m1~、correct_f1~等。)
df<-data.frame(test_l1 = c(1,0,0), test_l2=c(1,1,1), test_m1 = c(0,1,0), test_m2=c(0,1,1), l1=c(0,1,0), l2=c(1,1,1), m1=c(1,1,1), m2=c(0,0,1))
非常感谢!
发布于 2021-07-12 20:57:38
下面是一个你可以使用的tidyverse解决方案:
library(dplyr)
df %>%
mutate(across(starts_with("test_"), ~ .x == get(sub("test_", "", cur_column())),
.names = '{gsub("test_", "answer_", .col)}'))
test_l1 test_l2 test_m1 test_m2 l1 l2 m1 m2 answer_l1 answer_l2 answer_m1 answer_m2
1 1 1 0 0 0 1 1 0 FALSE TRUE FALSE TRUE
2 0 1 1 1 1 1 1 0 FALSE TRUE TRUE FALSE
3 0 1 0 1 0 1 1 1 TRUE TRUE FALSE TRUE发布于 2021-07-12 20:43:42
获取test_cols中的所有'test'列,从test_cols中删除字符串'test_'以获取要比较的相应列。
直接比较两个数据帧并创建新列。
test_cols <- grep('test', names(df), value = TRUE)
ans_cols <- sub('test_', '', test_cols)
df[paste0('correct_', ans_cols)] <- df[test_cols] == df[ans_cols]
df
# test_l1 test_l2 test_m1 test_m2 l1 l2 m1 m2 correct_l1 correct_l2 correct_m1 correct_m2
#1 1 1 0 0 0 1 1 0 FALSE TRUE FALSE TRUE
#2 0 1 1 1 1 1 1 0 FALSE TRUE TRUE FALSE
#3 0 1 0 1 0 1 1 1 TRUE TRUE FALSE TRUE其中TRUE表示答案是正确的,FALSE表示答案是错误的。
https://stackoverflow.com/questions/68347494
复制相似问题