R语言实现特定行的指定列转置为行的操作方法
R 实现方案
我们可以通过tidyverse套件的pivot_longer函数实现需求,代码如下:
首先加载依赖包:
library(tidyverse)
然后处理数据:
# 原始数据构造代码 df <- data.frame( student_id = c(1,1,1,2,2,2), question_id = c(10,11,12,20,21,22), score = c(2,3,4,2,1,5), C = c(NA,NA,1, NA,NA,1), E = c(NA,NA,2, NA,NA,1), O = c(NA,NA,1, NA,NA,3) ) # 数据处理逻辑 df_result <- bind_rows( # 第一部分:C/E/O全为NA的行,直接保留原有字段 df %>% filter(if_all(c(C,E,O), is.na)) %>% select(student_id, question_id, score), # 第二部分:C/E/O有有效值的行,宽转长处理 df %>% filter(if_any(c(C,E,O), ~!is.na(.))) %>% pivot_longer(cols = c(C,E,O), names_to = "suffix", values_to = "new_score") %>% mutate(question_id = paste0(question_id, "_", suffix), score = new_score) %>% select(student_id, question_id, score) ) %>% arrange(student_id, question_id)
执行后打印df_result即可得到目标输出:
> df_result # A tibble: 10 × 3 student_id question_id score <dbl> <chr> <dbl> 1 1 10 2 2 1 11 3 3 1 12_C 1 4 1 12_E 2 5 1 12_O 1 6 2 20 2 7 2 21 1 8 2 22_C 1 9 2 22_E 1 10 2 22_O 3
如果你的后缀列是A/B/C,只需要把代码中所有c(C,E,O)替换为c(A,B,C)即可。
内容的提问来源于stack exchange,提问作者amisos55
相关产品推荐
相关产品推荐

