从 R 中的整洁数据同时创建多个交互图

Creating several interaction plots simultaneously from tidy data in R

我有一个整洁的数据框,如下所示:

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 个因素(快乐、悲伤、愤怒)更多的因素,因此了解是否有有效生成这些因素的方法对我很有用。

使用此处的示例,我还需要 interaction.plot 函数中最后一项为 df$sad 和 df$angry 的绘图。 interaction.plot 函数中的前两项可以保持不变。

不是很优雅,但希望它清楚发生了什么以及如果您的请求有其他更改可以如何调整它。

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))