I'm trying to recode answers using a vector that contains the correct answers. I made a for loop that create a new column (with the coded answer) at each loop using a vector with the possible names for the new columns.
However, it seems that mutate does not receive vectors with names. I've tried some different vectors and some paste0() combinations but nothing seem to work.
Here is my reproduceable code:
library(dplyr)
library(tibble)
correct = c(4, 5, 2, 2, 2, 3, 3, 5, 4, 5, 2, 1, 3, 4, 2, 2, 2, 4, 3, 1, 1, 5, 4, 1, 3, 2)
sub1 = c(3, 5, 1, 5, 4, 3, 2, 5, 4, 3, 4, 4, 4, 1, 5, 1, 4, 3, 3, 4, 3, 2, 4, 2, 3, 4)
df = t(data.frame(sub1))
colnames(df) = paste0("P", 1:26)
new_names = paste0("P", 1:26, "_coded")
for(i in 1:26){
df = as.tibble(df) %>%
mutate(new_names = case_when(.[i] == correct[i] ~ 1,
.[i] != correct[i] ~ 0,
T ~ 9999999))
print(df) # to know what's going on.
}
Also, I know that .dots can receive names in a vector (I think), but I don't quite understand how to use it with case_when inside mutate().
Others ways to create new columns with the recoded value are welcome also
UPDATE: My expected output would be the original data frame with 26 new columns, P1_COD:P26_COD with possible values 1 (if correct) and 0 (if incorrect).
Something like this (I just created four columns with 1s and 0s as an example).
df %>%
mutate(P1_COD = 1,
P2_COD = 0,
P3_COD = 1,
P4_COD = 1)