0

I'm trying to create a loop in R that would create a dataframe with different name with each passing. I boiled down the problem to a simple example: Say I have 3 dataframes named a1, a2 and a3 and I would like to print them out in console using loop.

I came up with following code

a <- 1:3
for(i in a){
   a[[i]]
}

But I get a message that object of type 'closure' is not subsettable

A67John
  • 103
  • 7

1 Answers1

1

You can do

a1 <- data.frame(A = 1:3, B = 4:6)
a2 <- data.frame(A = 7:9, B = 10:12)
a3 <- data.frame(A = 13:15, B = 16:18)

for(i in 1:3) print(get(paste0("a", i)))
#>   A B
#> 1 1 4
#> 2 2 5
#> 3 3 6

#>   A  B
#> 1 7 10
#> 2 8 11
#> 3 9 12

#>    A  B
#> 1 13 16
#> 2 14 17
#> 3 15 18
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87