1

I have a list of data frames. I want to perform a bunch of operations within a for loop but before that, I need to extract the string name of each dataset to use as variable/data frame name suffixes.


for(i in dflist) { 
  
  suffix<- deparse(substitute(i))
    print(suffix)
  }

However, my output shows as the following:

[1] "i"
[1] "i"
[1] "i" 

I know that this is because of R's lazy evaluation framework. But how do I get around this limitation and get R to assign the names of data frames in dflist to the suffix variable ?

Smallex
  • 11
  • 1
  • 3
    `names(dflist)` or `names(dflist)[i]`? You shouldn't need to do any deparse(substitute()) nonsense... that's half the point of putting them in a list! – Gregor Thomas Nov 27 '21 at 05:22
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 27 '21 at 07:23

1 Answers1

0

You are almost there. Try to understand what elements of a list are and how indexing works when you works with lists.

example data

dflist <- list( 
     name_df1 = data.frame(a = 1:3)
    ,name_df2 = data.frame(mee = c("A","B","C","D"))
    )

understand list elements

What do we access with index i in a for loop over a list?

for(i in dflist){ 
  print(class(i))
  print(names(i))  
}
[1] "data.frame"
[1] "a"
[1] "data.frame"
[1] "mee"

index extracts an object of class (here) data frame.

your case

for(i in dflist){ 
  suffix <- names(i)
  print(suffix)  
}
[1] "a"
[1] "mee"
Ray
  • 2,008
  • 14
  • 21