How to convert the name of a dataframe to a string in R?

r

Solution

The only way I know to work this way directly on the dataframes in a list would be to attach a comment that holds the name, which you can then use to carry its name inside the loop:

df1 <- data.frame(var1=rnorm(10), var2=rnorm(10))
df2 <- data.frame(var1=rnorm(10), var2=rnorm(10))
comment(df1) <- "df1"
comment(df2) <- "df2"

for ( dataFrame in list(df1,df2) ) { 
     dFnm <- comment(dataFrame) 
     pdf(file=paste( dFnm, "_var1_vs_var2.pdf", sep="" ))
     plot( dataFrame[["var1"]], dataFrame[["var2"]] )     
     dev.off();
}

(You do lose the names of objects when they get passed as the loop variables. If you do `deparse(substitute())` inside that loop, you get "dataFrame" rather than the original names.) The other way would be to use names of the dataframes, but then you will need to use `get` or `do.call`, which might get a bit messier. This way seems fairly straightforward.

Problem

I am looping over a list of dataframes in R and want to use their names as part of the filename I save my plots under. The code below is my attempt at iterating through dataframes, plotting their first column (var1) versus their second (var2) and then saving the plot. ``` first.data = data.frame( var1 = 1:4, var2 = 5:8 ); second.data = data.frame( var1 = 9:12, var2 = 13:16 ); for ( dataFrame in list(first.data, second.data) ) { plot( dataFrame[["var1"]], dataFrame[["var2"]] ); dev.copy( pdf, paste( dataFrame, "_var1_vs_var2.pdf", sep="" ) ); dev.off(); } ``` I expect this loop to produce PDF files with filenames of the form "first.data_var1_vs_var2.pdf" but instead the name of the data frame is replaced with the first column in the frame and so I get something like "c(1, 2, 3, 4)_var1_vs_var2.exchemVbuffer.pdf".

Original source

Related problems