Search code examples
rplottidyrtidyverseinteraction

Creating several interaction plots simultaneously from tidy data in R


I have a tidy dataframe that looks like the following:

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

Here's the reproducible data:

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

I would like to create a series of interaction plots. So far, I have created interaction plots by spreading the data in the following way:

id  samediff  gainloss  happy  sad  angry 
1   S         G         5      3    4
2   D         G         2      3    5
3   D         L         1      4    3

I then use the following function:

interaction.plot(df$samediff, df$gainloss, df$happy) 

Is there a way to create separate interaction plots for each factor simultaneously? In my actual dataset, I have many more factors than the 3 listed here (happy, sad, angry), so it would be useful for me to know if there is a way to generate these efficiently.

Using the example here, I'd also need plots where the last term in the interaction.plot function is df$sad and df$angry. The first two terms in the interaction.plot function can stay the same.


Solution

  • Not very elegant but hopefully it's clear what's going on and how it can be tweaked if there are other changes to your request.

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

    enter image description here