一般来说,这是代码的新手,已经经历了数百次Google搜索和stackoverflow线程,但还没有什么真正能说明我的解决方案的工作原理。融合数据的方法有很多,大多数看起来过于复杂...很好奇为什么当所有其他解决方案都过于复杂时我的解决方案仍然有效。
原始数据框
> df <- data.frame(
ResponseID = c("123", "1234"),
Q1_W1 = c("Agree", "strongly disagree"),
Q1_W2 = c("disagree", "Agree"),
Q2_W1 = c("Disagree", "Disagree"),
Q2_W2 = c("Agree", "NA")
)
所需的输出
ResponseID variable value variable value
123 Q1_W1 agree Q2_W1 disagree
1234 Q1_W2 disagree Q2_W2 agree
我能够通过以下方式实现这一目标:
nalh5=ALH %>% gather(question,response, Q1_W1:Q1_W7)%>%
gather(q2, r2,Q2_W1:Q2_W3)%>%
gather(q3, r3, Q3_W1:Q3_W5)
它运作良好,但是有没有更有效的方法来实现这一目标?
我想这比较干净,但是在我看来,您正在屠宰已经整齐的数据集。
df %>%
pivot_longer(names_to = "Q1_questions",values_to = "Q1_answers",cols = contains("Q1")) %>%
pivot_longer(names_to = "Q2_questions",values_to = "Q2_answers",cols = contains("Q2"))
甚至可以将其变成函数
butcher_function <- function(df,Q) {
names_to_par <- str_c(Q,"questions",sep = "_")
values_to_par <- str_c(Q,"answers",sep = "_")
pivot_longer(data = df,
names_to = names_to_par,
values_to = values_to_par,
cols = contains(Q))
}
df %>%
butcher_function(Q = "Q1") %>%
butcher_function(Q = "Q2")