根据 R 中的文件名/条件创建不同的图

Create different plots based on file names / condition in R

我正在使用 R,我有一个向量存储目录中的文件名:

file_list <- c("loc1","loc2", ...)

我还有一个列表,存储每个位置的信息数据帧,例如。

head(flist[[1]])

       x     y1     y2      y3       y4
1    0.01000 0.1208 0.02161 0.00179 0.0002174
1232 0.03333 0.2250 0.09075 0.01507 0.0029956
45   0.05000 0.2868 0.14409 0.02998 0.0069587
1708 0.06667 0.3429 0.19718 0.04795 0.0123678
1842 0.07500 0.3690 0.22315 0.05776 0.0155406
15   0.10000 0.4407 0.29743 0.08934 0.0265723

(文件名索引对应flist中元素的索引)

每个文件的信息都可以与其他一些文件进行比较,但不是全部。所以我创建了 4 个组:

g1 = "loc5"
g2 = c("loc1","loc4","loc10") 
...

等等

我想在一个图上绘制 "loc1"、"loc4" 和 "loc10" 的 x 与 y4,"loc2" 和 [= 的 x 与 y3 35=] 在另一个地块上,等等

但是,我似乎找不到比 for 循环遍历文件列表并分配许多嵌入式 'ifs' 来测试每个单独的文件名更麻烦的事情了。

我想知道是否有一种方法可以自动创建四个空图(或子图),然后根据文件名(例如 file_list 在适当的图上调用 plot 命令[一世])。

或者任何其他有效的方法都欢迎!

好的。首先,这里有一些符合您描述的虚拟数据

# vector with file names, and list of data frames for each file
file_list <- paste0('loc', 1:10)
flist <- lapply(1:10, function(dummy) data.frame(x=runif(6), y3=runif(6), y4=runif(6)))

# file groups to plot
g1 <- "loc5"
g2 <- c("loc1","loc4","loc10")

这是我解决问题的方法

# first, add a column to each data frame with the file name
for(i in seq_along(flist)) flist[[i]]$file <- file_list[i]

# now a function that extracts data for a given group to a single data.frame
# and plots x vs a given y variable
library(ggplot2)

plot_group <- function(g, yvar) {
  plot_data <- do.call(rbind, flist[file_list %in% g])

  ggplot(plot_data, aes_string(x='x', y=yvar, color='file')) +
    geom_point() + theme_classic()
}

plot_group(g2, 'y4') 给你: