如何在for loop中使用dataframe名称在R中保存不同的ggplot2绘图
我有一个数据帧(all.table),我将其子集为3个不同的数据图名称(A1.table、B25.table和C48.table) 对于我想要的每种图形类型,我想基于所有4个表生成它如何在for loop中使用dataframe名称在R中保存不同的ggplot2绘图,r,for-loop,dataframe,ggplot2,R,For Loop,Dataframe,Ggplot2,我有一个数据帧(all.table),我将其子集为3个不同的数据图名称(A1.table、B25.table和C48.table) 对于我想要的每种图形类型,我想基于所有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_out
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和A1.table.graph1.pdf、A1.table.graph2.pdf等的某种形式
我的问题是如何将迭代器I
的名称转换为字符串,并将该字符串添加到'.graph1.pdf'
字符串中
从python的背景来看,这似乎应该相当简单。我对R不是很精通(从这个问题可以明显看出),我发现任何类似于答案的东西似乎都太复杂了。这是一个使用
tidyverse
功能套件的工作流iwalk
类似于base中的lappy
,但它需要一个接受两个参数的函数,并自动输入列表的名称作为第二个参数。您需要的简短答案是
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")))
})
通过寻找与python字典等效的解决方案:
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")
#Generate a named list of tables
list_of_tables = list(all = all.table, A1 = A1.table, B25 = B25.table, C48 = C48.table)
for (i in 1:length(list_of_tables)){
ggplot(list_of_tables[[i]], aes(x=Frequency, fill=Category)) + #more options
ggsave(file.path(full_output_path, paste0(names(list_of_tables[i]), ".graph1.pdf"))
}
我不确定是否不使用其他库(即<代码> TyDyError <代码>),但这似乎是最简单的答案。
如果这三个IDS耗尽了所有可能的ID,请考虑< <代码> > <代码> >拆分< /代码>,避免将这些子集表保存在内存中:<代码>拆分(ALL表,ALL。表$ ID)< /C>或<代码>(all.table,all.table$ID,identity)。事实上,它们都创建了子集dfs的命名列表,对于,通过将identity替换为一个函数来运行ggplot
调用。
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")
#Generate a named list of tables
list_of_tables = list(all = all.table, A1 = A1.table, B25 = B25.table, C48 = C48.table)
for (i in 1:length(list_of_tables)){
ggplot(list_of_tables[[i]], aes(x=Frequency, fill=Category)) + #more options
ggsave(file.path(full_output_path, paste0(names(list_of_tables[i]), ".graph1.pdf"))
}