基于现有列创建多个新列(dplyr)

Creating multiple new columns based on existing columns (dplyr)

我正在尝试自动创建变量来指示学生对问题(例如以“test_”开头的变量)的回答(以 l、m、f 或 g 开头的变量)是否正确。 IE。这是通过检查是否 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~ etc.)

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

非常感谢!!!

获取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 表示答案错误。

您可以使用以下 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