使用R语言dplyr计算多组对两个问卷问题的回答差异
解决方案
要实现你需要的计算逻辑(同一Area、Section、Response分组下,Q2的数值减去Q4的数值),可以用以下两种简洁的方法:
方法一:宽表转换后计算
先将数据转换为宽表,把Question作为列名,再直接计算差值:
library(tidyverse) df %>% pivot_wider( id_cols = c(Area, Section, Response), names_from = Question, values_from = c(G1, G2) ) %>% mutate( G1 = G1_Q2 - G1_Q4, G2 = G2_Q2 - G2_Q4 ) %>% select(Area, Section, Response, G1, G2)
方法二:分组后汇总计算
按Area、Section、Response分组,提取Q2和Q4的数值做差:
df %>% group_by(Area, Section, Response) %>% summarize( G1 = first(G1[Question == "Q2"]) - first(G1[Question == "Q4"]), G2 = first(G2[Question == "Q2"]) - first(G2[Question == "Q4"]), .groups = "drop" )
原方法失效原因
你之前的group_by(Question, Response)分组逻辑错误,应该按**需要保留的维度(Area、Section、Response)**分组,而不是按Question分组——按Question分组后,每个组里只有单个Question的数据,lag自然取不到另一Question的数值。
两种方法都能得到你想要的wanted结果,且适配实际数据中更多区域和分组的场景。
内容的提问来源于stack exchange,提问作者GeoffRussell
相关产品推荐
相关产品推荐

