I have a very basic question on how to create a function and loop it in R.
Given my data with:
#create a test df
a<-c(1,2,3,4,5,6,7)
b<-c(1,2,4,4,5,6,7)
c<-c(1,7,1,7,2,5,4)
d<-c(1,7,1,7,2,5,4)
df.abcd<-data.frame(a,b,c,d)
I want to automatically create Boxplots and save their outputs. It works fine like this:
# Create Boxplots from all columns
for (x in 1:length(df.abcd)) {
windows()#opens a graphics window - necesarry for the plots
boxplot(df.abcd[,x],
main=names(df.abcd)[x])#writes colnames as title
savePlot(filename=paste("E:\\R\\2_outputs\\boxplot_,deparse(x)), type="tiff")
dev.off()#disables the graphics window
}
Now I would like to make my procedure a function so that I can apply it on several Dataframes without repeating my code. I thought of someting like:
#make the above a function and apply it
test.function<-function(y){
for (x in 1:length(y)){
windows()
boxplot(y[,x],
main=names(y)[x])
savePlot(filename=paste("E:\\R\\2_outputs\\boxplot_,deparse(x)), type="tiff")
dev.off()
}}
test.function(df.abcd)
So in the end this function works but it doesn’t loop any more. Only the first column of my dataframe is created as an output.
What am I doing wrong?
you have some mistakes in your code. (change x to y and add ” for the path name).
This should work:
it is better to do something like this ( it the same as @Joris answer, maybe it is better to use tiff directly here)