Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - print name of object in a for loop

Tags:

for-loop

r

I'm applying some code to a number of files using a for loop in R. I want to save an output file after each iteration of the loop, named according to the file being processed in that iteration of the loop. How do I print the name of the file being used in each round of the loop?

My understanding of a for loop is that you supply it with a list and some code, it then runs through each item on the list and applies the code to it. So it seems to me that I should be able to pull out the name of the item on the list being used in each round of the loop. Please correct me if this is wrong.

After a lot of searching, this is the closest I've been able to get:

# load lines files
csv1 <- read.csv("csv1.csv")
csv2 <- read.csv("csv2.csv")

# make list of lines files
object.list <- list(csv1, csv2)

for(i in object.list){
  print(deparse(substitute(i)))
}

Which produces:

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

But I want it to produce:

[1] "csv1"
[1] "csv2"

Any ideas? Simple examples please.

like image 568
Thomas Avatar asked Oct 15 '25 13:10

Thomas


1 Answers

What about naming the elements of the list :

# load lines files
csv1 <- "file content"
csv2 <- "some other file content"

# make list of lines files
object.list <- list(csv1 = csv1, csv2 = csv2)

for(name in names(object.list)){
  print(name)
  print(object.list[[name]])
}
like image 169
Waldi Avatar answered Oct 19 '25 13:10

Waldi