n8sty
n8sty

Reputation: 1438

Performing same action on multiple tables in for loop

This is a very simplified version of what I'm trying to do. In brief, I create some matrices that I want to perform the same action on, like in a loop. In this example here I want to print the summary for each matrix, but I don't know how to refer to the matrices in a for loop. Any help is much appreciated:

for (i in 1:3){
  x <- paste0('df', i)
  assign(x, matrix(sample(1:10, 15, replace = TRUE), ncol = 3))
  print(summary(eval(x)))
}

Returns (it is evaluating 'df3' as a string):

   Length     Class      Mode 
        1 character character 
   Length     Class      Mode 
        1 character character 
   Length     Class      Mode 
        1 character character

How do I get it to return the following?

       V1             V2            V3    
 Min.   : 1.0   Min.   :3.0   Min.   : 5  
 1st Qu.: 5.0   1st Qu.:3.0   1st Qu.: 5  
 Median : 6.0   Median :4.0   Median : 7  
 Mean   : 5.6   Mean   :5.2   Mean   : 7  
 3rd Qu.: 6.0   3rd Qu.:7.0   3rd Qu.: 8  
 Max.   :10.0   Max.   :9.0   Max.   :10 

       V1          V2            V3      
 Min.   :2   Min.   :1.0   Min.   : 4.0  
 1st Qu.:4   1st Qu.:3.0   1st Qu.: 4.0  
 Median :7   Median :3.0   Median : 6.0  
 Mean   :6   Mean   :3.4   Mean   : 6.6  
 3rd Qu.:8   3rd Qu.:4.0   3rd Qu.: 9.0  
 Max.   :9   Max.   :6.0   Max.   :10.0  

       V1            V2             V3     
 Min.   :1.0   Min.   : 5.0   Min.   :1.0  
 1st Qu.:2.0   1st Qu.: 6.0   1st Qu.:2.0  
 Median :6.0   Median : 6.0   Median :3.0  
 Mean   :5.2   Mean   : 6.8   Mean   :2.4  
 3rd Qu.:8.0   3rd Qu.: 7.0   3rd Qu.:3.0  
 Max.   :9.0   Max.   :10.0   Max.   :3.0  

Upvotes: 0

Views: 146

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545618

Don’t use distinct variables and paste their names – put your objects into a list:

x = Map(function (i) matrix(sample(1:10, 15, replace = TRUE), ncol = 3), 1 : 3)

Then performing a common operation on them is trivial as well:

Map(summary, x)

Map maps a function onto a list. It operates similar to the lapply and mapply family of functions.

Upvotes: 5

Julien Navarre
Julien Navarre

Reputation: 7830

I think you can use eval(as.name("df3")) or get("df3")

Upvotes: 1

Related Questions