我有以下数据

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

这是我的第一行数据:

enter image description here

我想用下面的逻辑将其转换为长格式.对于每个参与者,有12行,因为有4个任务(4个)和每个任务(3个P)中的3个配置文件.CHOICE列是一个二进制,如果该行中的配置文件是在该任务中 Select 的,则为1,如果不是,则为0,这是‘TN_CHOICE’列中包含的信息.

enter image description here

我的方法是错误的

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
}

推荐答案

也许你可以试试这个

data %>%
    pivot_longer(-id) %>%
    summarise(choice = list(+(seq(3) == value)), .by = c(id, name)) %>%
    unnest(choice) %>%
    print(n = 1000000L) # just to print more rows

这给了我们

   id                name      choice
   <chr>             <chr>      <int>
 1 R_88j7lG37gLfxk22 t1_choice      0
 2 R_88j7lG37gLfxk22 t1_choice      1
 3 R_88j7lG37gLfxk22 t1_choice      0
 4 R_88j7lG37gLfxk22 t2_choice      1
 5 R_88j7lG37gLfxk22 t2_choice      0
 6 R_88j7lG37gLfxk22 t2_choice      0
 7 R_88j7lG37gLfxk22 t3_choice      1
 8 R_88j7lG37gLfxk22 t3_choice      0
 9 R_88j7lG37gLfxk22 t3_choice      0
10 R_88j7lG37gLfxk22 t4_choice      0
11 R_88j7lG37gLfxk22 t4_choice      1
12 R_88j7lG37gLfxk22 t4_choice      0
13 R_6DK8lERVf8lSQf4 t1_choice      0
14 R_6DK8lERVf8lSQf4 t1_choice      0
15 R_6DK8lERVf8lSQf4 t1_choice      1
16 R_6DK8lERVf8lSQf4 t2_choice      0
17 R_6DK8lERVf8lSQf4 t2_choice      0
18 R_6DK8lERVf8lSQf4 t2_choice      1
19 R_6DK8lERVf8lSQf4 t3_choice      0
20 R_6DK8lERVf8lSQf4 t3_choice      1
21 R_6DK8lERVf8lSQf4 t3_choice      0
22 R_6DK8lERVf8lSQf4 t4_choice      1
23 R_6DK8lERVf8lSQf4 t4_choice      0
24 R_6DK8lERVf8lSQf4 t4_choice      0

R相关问答推荐

基于R中的GPS点用方向箭头替换点

提取R中值和列名的所有可能组合

按R中的组查找相邻列的行累积和的最大值

如何在ggplot 2线性图的每个方面显示每个组的误差条?

如何在RMarkdown LaTex PDF输出中包含英语和阿拉伯语?

pickerInput用于显示一条或多条geom_hline,这些线在图中具有不同 colored颜色

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

计算数据帧中指定值之前的行数,仅基于每行之后的future 行,单位为r

函数可以跨多个列搜索多个字符串并创建二进制输出变量

有没有办法一次粘贴所有列

使用列中的值来调用函数调用中应使用的其他列

向R中的数据帧添加一列,该列统计另一列中每个唯一值的二进制观测值的数量

构建一个6/49彩票模拟系统

替换在以前工作的代码中有x行&q;错误(geom_sf/gganimate/dow_mark)

将数据从一列转换为按组累计计数的单个虚拟变量

有没有办法将勾选/审查标记添加到R中的累积关联图中?

使用dqur在不同变量上创建具有多个条件的变量

根据向量对列表元素进行排序

如果缺少时间,如何向日期-时间列添加时间

在shiny /bslb中,当卡片是从json生成时,如何水平排列卡片?