Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R dynamic data frame names in Loop

I have some df like

df1
df2
df3
...
dfn

So how to use my data frame using loop

example:

loop (i in 1:n)
{
summary (paste0 ("df",i)) # =====> It dose not work!

}

like image 623
Tuong Nguyen Avatar asked May 22 '17 10:05

Tuong Nguyen


1 Answers

We can use mget to return the value of the string objects in a list, then loop through the list with lapply get the summary

lapply(mget(paste0("df", seq_len(n))), summary)

If we are using a for loop, make sure that we store the results in an object, preferably a list, use get to return the value of the object, get the summary and store it as list element in the 'out' object

out <- vector('list', n)
for(i in seq_len(n)) {
   out[[i]] <- summary(get(paste0("df", i)))
 }

NOTE: It is better to have all the data.frame in a list. But, in case we want to update the original objects in the global environment using for loop use assign

for(i in seq_len(n)) {
  assign(paste0("df", i), get(paste0("df", i))[-(1:3)])
 }   

Or this can be done with list2env after using lapply

list2env(lapply(mget(paste0("df", seq_len(n))), function(x) x[-(1:3)]), .GlobalEnv)

data

df1 <- data.frame(col1 = 1:3, col2 = 4:6, col3 = 7:9, col4 = 10:12)
df2 <- data.frame(col1 = 1:15, col2 = 16:30, col3 = 31:45, col4 = 46:60)
n <- 2
like image 150
akrun Avatar answered Nov 03 '22 08:11

akrun