首页 > 解决方案 > 如何在for循环中使用数据框名称在R中保存不同的ggplot2图

问题描述

我有一个数据框(all.table),我已将其子集为 3 个不同的数据图名称(A1.table、B25.table 和 C48.table)

all.table = read.table(file.path(input_file_name), header=T, sep = "\t")
A1.table = subset(all.table, ID == "A1")
B25.table = subset(all.table, ID == "B25")
C48.table = subset(all.table, ID == "C48")

对于我想要的每种图形类型,我想根据所有 4 个表生成它

for (i in list(all.table, A1.table, B25.table, C48.table)){
    ggplot(i, aes(x=Position, fill=Frequency)) + #other plot options
    ggsave(file.path(full_output_path, "uniqueFileName.pfd")
    #additional plots
    #additional saves
    }

我的问题出现在 ggsave 命令中,如何生成“uniqueFileName.pdf”。我想将其命名为 all.table.graph1.pdf、all.table.graph2.pdf 和 A​​1.table.graph1.pdf、A1.table.graph2.pdf 等的某种形式

我的问题是如何将迭代器的名称i转换为字符串,并将该字符串添加到'.graph1.pdf'字符串中?

来自 python 背景,这看起来应该相当简单。我对 R 不是很精通(从这个问题中可能很明显),任何类似于我找到的答案的东西似乎都非常复杂。

标签: rfor-loopdataframeggplot2

解决方案


这是一个使用tidyverse这套功能的工作流程。 iwalk类似于lapplyin base,但它需要一个带有 2 个参数的函数,并且它会自动输入列表的名称作为第二个参数。
您想要的简短答案是paste0,它可以让您组合字符串。

library(tidyverse)
all.table %>%
  filter(ID %in% c("A1", "B25", "C48")) %>% # only needed if there are more IDs than the 3 explictly listed
  split(., .$ID) %>% # creates the list of data frames
  c(list(all.table = all.table), .) %>% # adds "all.table" as a list element
  iwalk(function(df, label) {
    ggplot(df, aes(x = Position, fill = Frequency)) + 
      ...
    ggsave(file.path(full_output_path, paste0(label, ".graph1.pdf")))
  })

推荐阅读