如何基于列索引为tibble添加指定列的取值列?
解决方案
你的核心需求是根据每行对应的列索引,提取该行对应列的数值。当前代码的问题在于select(df, index)是在整个数据框层面选择列,而非按行提取对应位置的元素。以下是几种可行的实现方法:
方法一:使用dplyr行分组+跨列提取
library(dplyr) question <- c("q1","q2","q3","q4") a <- c("no","no","yes","no") b <- c("yes","yes", "no","no") c <- c("no","no","no","yes") index <- c(3,3,2,4) df <- tibble(question,a,b,c) df <- df %>% rowwise() %>% mutate(answer = c_across(all_of(index))) %>% ungroup()
说明:rowwise()将数据框按行分组后,c_across(all_of(index))会针对每行提取index指定列的元素,最后用ungroup()取消行分组,避免影响后续操作。
方法二:Base R矩阵索引实现
# 基于原数据框构造矩阵,提取对应位置元素 df$answer <- as.matrix(df[, -1])[cbind(1:nrow(df), index - 1)]
说明:将除question外的列转为矩阵后,cbind(1:nrow(df), index - 1)生成每行的行号与矩阵列号(原数据框列索引减1,对应矩阵的列位置),直接提取对应元素。
方法三:使用purrr遍历行与索引
library(purrr) df$answer <- map2_chr(1:nrow(df), index, ~ df[.x, .y])
说明:map2_chr同时遍历行号和对应的索引值,逐行提取对应列的元素,返回字符向量直接赋值给新列。
运行任意一种方法后,均可得到你期望的结果:
| question | a | b | c | answer |
|---|---|---|---|---|
| q1 | no | yes | no | yes |
| q2 | no | yes | no | yes |
| q3 | yes | no | no | yes |
| q4 | no | no | yes | yes |
内容的提问来源于stack exchange,提问作者AdrieSC
相关产品推荐
相关产品推荐

