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

前端 未结 3 1719
余生分开走
余生分开走 2020-12-28 18:28

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 thro

3条回答
  •  一个人的身影
    2020-12-28 18:59

    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.

提交回复
热议问题