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")

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

	plot(data$Angle, col)	# 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):


map(names(mtcars)[names(mtcars) != "mpg"],
    ~ {
      plot(mtcars$mpg, mtcars[[.x]])

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

lapply(names(mtcars)[names(mtcars) != "mpg"],
       function(var) {
         plot(mtcars$mpg, mtcars[[var]])

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.