【R】Rscript中使用变量控制输入输出的文件名
在R输入输出控制中不可避免地将变量引入输出文件名中,这种输出的文件名在Rscript中应该如何加入变量?
library(ggplot2) library(dplyr) library(tidyr) for (i in 10:21){ file <- paste("result_", i, sep="") out_file <- paste(file, ".out", sep="") out_file2 <- paste(file, ".plot", sep="") plot_file <- paste(file, ".pdf", sep="") df <- read.table(file, header=FALSE) df_spread <- tidyr::spread(df, V3, V1) #write.table(df_spread, file=out_file,row.names = FALSE, quote =FALSE, sep="\t") df_change <- df %>% group_by(V3) %>% mutate(V6 = log2(V1 / V5)) Title <- df[1,4] write.table(df_change, file=out_file2,row.names = FALSE, quote =FALSE, sep="\t") plot <- ggplot(df_change, aes(x=V3,y=V6,fill=V2)) + geom_col(position= "dodge") + theme_classic() + theme(axis.text.x = element_text(size = 7),axis.text.y = element_text(size = 7), strip.text = element_text(size=10, color = "black"),axis.title.y = element_text(size=11, color = "black"), strip.text.y=element_text(size=9, color = "black"), panel.spacing = unit(0.1, "lines"), panel.grid = element_blank(),legend.text = element_text(size = 8),legend.background = element_blank())+ xlab(Title) + ylab("log2(fold change)") +scale_fill_brewer(palette = "Set3") ggsave(file=plot_file,plot,width = 8,height = 4, units = "in") }
这里循环变量i可以使用.paste()函数将变量与前缀后缀组合在一起,形成新的文件名。此处要注意参数“sep=”要加,如果没有间隔就是""。