代码之家  ›  专栏  ›  技术社区  ›  melbez

从r中的tidy数据同时创建多个交互图

  •  0
  • melbez  · 技术社区  · 6 年前

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

    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函数中的前两个项可以保持不变。

    1 回复  |  直到 6 年前
        1
  •  1
  •   MHammer    6 年前

    不是很优雅,但希望它是清楚的,如果你的请求有其他变化,它可以如何调整。

    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