我有以下数据
data<-structure(list(id = c("R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4"
), t1_choice = c("2", "3"), t2_choice = c("1", "3"), t3_choice = c("1",
"2"), t4_choice = c("2", "1")), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame"))
这是我的第一行数据:
我想用下面的逻辑将其转换为长格式.对于每个参与者,有12行,因为有4个任务(4个)和每个任务(3个P)中的3个配置文件.CHOICE列是一个二进制,如果该行中的配置文件是在该任务中 Select 的,则为1,如果不是,则为0,这是‘TN_CHOICE’列中包含的信息.
我的方法是错误的
tasks<-4
profiles<-3
#column position of first task
cpft<-2
#column position of last task
cplt<-5
# Extracting choices
choices <- as.numeric(unlist(long[, cpft:cplt]))
# Create the new dataframe with id and choice columns
new_df <- data.frame(
id = rep(data$id, each = tasks*profiles),
choice = rep(0, times = length(id))
)
# Replacing values based on original choices
for (i in 1:(tasks*profiles)) {
idx <- (i - 1) * profiles + choices[i]
new_df$choice[idx] <- 1
}