我的数据框看起来很整洁,如下所示:
id samediff gainloss factor value
1 S G happy 5
1 S G sad 3
1 S G angry 4
2 D G happy 2
2 D G sad 3
2 D G angry 5
3 D L happy 1
3 D L sad 4
3 D L angry 3
以下是可重现的数据:
df<- data.frame(id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
samediff = c("S", "S", "S", "D", "D", "D", "D", "D", "D"),
gainloss = c("G", "G", "G", "G", "G", "G", "L", "L", "L"),
factor = c("happy", "sad", "angry", "happy", "sad", "angry", "happy", "sad", "angry"),
value = c(5, 3, 4, 2, 3, 5, 1, 4, 3))
我想创建一系列交互图。到目前为止,我已经通过以下方式传播数据来创建了交互图:
id samediff gainloss happy sad angry
1 S G 5 3 4
2 D G 2 3 5
3 D L 1 4 3
然后我使用以下功能:
interaction.plot(df$samediff, df$gainloss, df$happy)
是否可以同时为每个因子创建单独的交互图?在我的实际数据集中,与这里列出的3个因素相比,我有更多的因素(快乐,悲伤,愤怒),因此对于我是否有办法有效地生成这些因素很有用。
使用此处的示例,我还需要图,其中interact.plot函数中的最后一项是df $ sad和df $ angry。 interact.plot函数中的前两个术语可以保持不变。
答案 0 :(得分:1)
不太优雅,但希望可以弄清楚发生了什么,如果请求有其他更改,可以如何进行调整。
df <- data.frame(id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
samediff = c("S", "S", "S", "D", "D", "D", "D", "D", "D"),
gainloss = c("G", "G", "G", "G", "G", "G", "L", "L", "L"),
factor = c("happy", "sad", "angry", "happy", "sad", "angry", "happy", "sad", "angry"),
value = c(5, 3, 4, 2, 3, 5, 1, 4, 3))
df_2 <- tidyr::spread(df, factor, value)
# Unique values of factor to iterate over and obtain interaction plots for
factor_values <- unique(df$factor)
size <- ceiling(sqrt(length(factor_values)))
par(mfrow = c(size, size))
for(i_factor_value in factor_values) {
interaction.plot(df_2$samediff, df_2$gainloss, df_2[[i_factor_value]], ylab = i_factor_value)
}
par(mfrow = c(1, 1))