不是很优雅,但希望它是清楚的,如果你的请求有其他变化,它可以如何调整。
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))