Name files based off data columns

I am trying to draw a set of graphs, and save them with sensible names.
This code does work, but is not very elegant. How can I rewrite this so that it only has one list, and doesn't require a variable that is incremented?

data <- read.csv("rotation_data.csv", header = TRUE)
colnames <- list(data$Ethane,data$dichloroethane,data$Butane)
colnames2 <- list("Ethane","dichloroethane","Butane")

i=0
for(col in colnames){
 
	postscript(paste(colnames2[i],".eps"))	# create a new file to save to

	plot(data$Angle, col)

	dev.off()	# close the graphics device used to create and write to the file
	i <- i+1
}

In the code below, I use map from the purrr package to iterate over each column name, instead of a for loop. I've used the built-in mtcars data frame for illustration. We need the column names to name the files and select the columns for plotting, but we can get those on the fly with names(mtcars). We exclude the mpg column, because that one appears in every plot (we're using it as the equivalent of Angle in your example):

library(tidyverse)

map(names(mtcars)[names(mtcars) != "mpg"],
    ~ {
      postscript(paste0(.x,".eps"))
      plot(mtcars$mpg, mtcars[[.x]])
      dev.off()
    })

If you're more familiar with base R, the equivalent code using lapply would be:

lapply(names(mtcars)[names(mtcars) != "mpg"],
       function(var) {
         postscript(paste0(var,".eps"))
         plot(mtcars$mpg, mtcars[[var]])
         dev.off()
       })

Thanks! I was not aware of the lapply function, but it makes a lot more sense than what I was trying to do.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.