【问题标题】:Loop in R to produce graph for every combination of variables of different length在 R 中循环为不同长度的变量的每个组合生成图形
【发布时间】:2021-08-07 05:43:58
【问题描述】:

我正在尝试创建一个函数,该函数将生成一个单独的图,比较 type = "Plot" 到 type = "Strata" 的两个线性回归。这种线性模型的比较必须针对 BCR # 和 LC 类型的每个独特组合进行。例如(LC = UC 和 BCR = 30,LC = UC 和 BCR = 29,LC = UC 和 BCR = 28...一旦比较了每个唯一 BCR 的 LC“UC”,那么循环应该继续下一个 LC 类型并将其与所有 BCR #s 进行比较)。下面是我的数据框:

> head(Plot_BCR)
# A tibble: 6 x 5
   Year   BCR LC      Area type 
  <dbl> <int> <chr>  <dbl> <chr>
1  2001    30 UC    0      Plot 
2  2001    30 OW    0      Plot 
3  2001    30 D1    0.0126 Plot 
4  2001    30 D2    0      Plot 
5  2001    30 D3    0      Plot 
6  2001    30 D4    0      Plot 

> unique(Plot_BCR$LC)
 [1] "UC" "OW" "D1" "D2" "D3" "D4" "BL" "DF" "EF" "MF" "SS" "H"  "HP" "CC" "WW" "EW"

> unique(Plot_BCR$BCR)
[1]  30  29  28  14  13 100  27  31

我创建了以下函数和嵌套循环来创建每个唯一组合,但是我的输出只为每个 LC 类型生成一个图表,但只为最后一个 BCR # (#31)。

comparison.graph <- function(Plot_BCR, na.rm=TRUE, ...){
  
  BCR <- unique(Plot_BCR$BCR)
  LC <- unique(Plot_BCR$LC)
  
  for (i in seq_along(LC)){
    for (j in seq_along(BCR))
    plot <-
      ggplot(subset(Plot_BCR, Plot_long$LC == LC[i] & BCR == BCR[j]), aes(x = Year, y = Area, group=type))+
      geom_smooth(method="lm", formula=y~x)+
      ggtitle(paste(LC[i], BCR[j], sep="-"))
    
    print(plot)
  }
}

comparison.graph(Plot_BCR)

如果对我的函数有任何帮助,如果它会为 LC 和 BCR # 的每种组合创建一个绘图,我们将不胜感激。

【问题讨论】:

    标签: r function loops


    【解决方案1】:

    您可以使用split + lapply 方法生成绘图列表。

    library(ggplot2)
    
    comparison.graph <- function(Plot_BCR, na.rm=TRUE, ...){
      
      lapply(split(Plot_BCR, list(Plot_BCR$LC,Plot_BCR$BCR)), function(data) {
        ggplot(data, aes(x = Year, y = Area, group=type)) +
          geom_smooth(method="lm", formula=y~x)+
          ggtitle(paste(data$LC[1], data$BCR[1], sep="-"))
      })
    }
    
    list_plots <- comparison.graph(Plot_BCR)
    

    我们 split 将数据放入数据帧列表中,其中每个数据帧是 LCBCR 的唯一值的组合,并绘制每个数据帧的数据。可以通过[[list_plots[[1]]list_plots[[2]] 等访问各个图。

    【讨论】:

    • 完美运行!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    相关资源
    最近更新 更多