As I learn R, I am trying to use it in my work. I needed to plot 142 plots and do some stats. Therefore I decided to write the following function:
Melting <- function(df){
i <- as.character(substitute(df))
df.m<-melt(df)
library(grid, lib.loc = "C:/Program Files/R/R-3.6.2/library")
name_plot = paste(i,".png",sep = "")
png(name_plot, width = 10, height = 9, units = 'in', res = 700)
print(ggplot(data = df.m, aes(x=Tissuetype, y=value)) + geom_boxplot(aes(fill=variable)) + stat_compare_means(aes(group = variable), label = "p.signif") + theme(axis.text.x = element_text(angle = 90)))
dev.off()
}
The function runs fine and takes one of the dataframe present in my environment as an input. For eg: Melting(liver)
Having tested that the function successfully plot the graph, I decided to put it in a for
loop as I did in bash scripting. However, it throws the following error:
for(i in names){Melting(i)}
Error in FUN(X[[i]], ...) : object 'variable' not found
The names vector was created as follows
files = list.files(pattern = "*.csv")
names <-tools::file_path_sans_ext(files)
I have a hunch that the value of I in for loop is getting substituted as string eg: Melting("liver") rather than an argument Melting(liver). But I don't know how to get over it. I read several posts but couldn't understand. Please help