How do I find the sizes of variables that have a fixed sequential format in R?

I have multiple frames of data stored in my environment at different sizes. However, these data frames have similar names, such as a1

, a2

, a3

, etc. Before a10

.

Now, instead of doing dim(a1)

, dim(a2)

for each dataframe, I want to prepare a loop that can give me a measurement of all those dataframes at the same time. I used the following code:

for (i in 1:10) {
  dim(get(paste0("a", i)))
}

      

However, this gives no result. Please, help

+3


source to share


2 answers


You can use lapply

to store the output of the loop in a list:



lapply(paste0("a", c(1,10)), function(x)dim(get(x)))

      

+2


source


@ user1981275 The answer reminded me that I always forget get()

for()

loops in R are not often a good idea.

First, set the data frames to the list:

dfs <- ls(pattern = "a")

      



Then, lapply()

above that list:

lapply(dfs, function(x) {dim(get(x))})

      

If you have other objects loaded into your environment with "a" in your match pattern =

then you need to be more complex

+2


source







All Articles