R - print name of object in a for loop

Viewed 1341

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.

3 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]])
}

I do not believe there is a direct way of doing it. R does not remember that i has been created using csv1 and csv2. It only knows the values. Maybe this workaround works for you:

object.list <- list(csv1, csv2)
names(object.list) <- c( substitute(csv1), substitute(csv2))

for(i in 1:length(object.list){
  print(names(object.list[i]))
}

Adding the original variables as names you can access them later.

You may be better served by changing your work flow... Here's an example using some csv files I have laying around

# You could also do this via a system call
# No need for a list a vector will do
files_to_read <- c("bfwicox.csv", "churn.csv")
# Name automatically
names(files_to_read) <- files_to_read

# Now run loop
for(name in names(files_to_read)){
  data <- read.csv(files_to_read[[name]])
  print(paste("This is a summary of the first two variables in file...", 
              files_to_read[[name]]))
  print(summary(data[1:2]))
}

[1] "This is a summary of the first two variables in file... bfwicox.csv"
       X             income      
 Min.   :    1   Min.   :  1100  
 1st Qu.: 4250   1st Qu.: 25000  
 Median : 8500   Median : 40000  
 Mean   : 8500   Mean   : 50687  
 3rd Qu.:12750   3rd Qu.: 65000  
 Max.   :16999   Max.   :250000  
[1] "This is a summary of the first two variables in file... churn.csv"
      ID               ACLENGTH    
 Length:5000        Min.   :  0.0  
 Class :character   1st Qu.: 73.0  
 Mode  :character   Median :100.0  
                    Mean   :100.9  
                    3rd Qu.:127.0  
                    Max.   :227.0  

Related