Home > Blockchain >  Call multiple dataframes stored in list for a For Loop
Call multiple dataframes stored in list for a For Loop

Time:11-30

I don't know if this is actually feasible but I need to find a workaround for this problem. I have several dataframes stored in a list that were generated by something like this:

SSE <- list()
for (i in cms){
  SSE[[paste0("SE",i)]] <- subset(DF, DF$X == i)
}

where cms is a vector that stores the DF$X values I need. So I end up with a list SSE what has many dataframes that I can use with SSE[["SE1"]] for example.

Now my problem is I want to use all the dataframes is SSE on another for loop and I don't know how to call these. This is an simplified example of what I want to do:

for (i in cms){
    SSE[["SE[[i]]"]] <- arrange(SE[["SE[[i]]"]], y)
    SSE[["SE[[i]]"]][105,4] <- tail(na.omit(SSE[["SE[[i]]"]]$Nump),1)
}

The actual operations I need to make are a lot more and way more complex than this, so if this isn't actually doable it would be easier for me to re create each dataframe individually instead of a creating them inside a list.

If anyone can tell me how to call these listed dataframes on the second for loop or how to modify the first for loop to create these dataframes individually (as I think I should be able to call those on the second loop) I would greatly appreciate it.

Thanks to anyone reading this!

CodePudding user response:

First without seeing a sample of your data it is difficult to provide specific advice. What is SE, cms and DF?

First you could use split() to avoid the loop to split the initial data frame. Then either use lapply() for loop through the list or use names(SSE) to obtain a vector of list elements names.

#using fake data
DF <- mtcars
cms <- unique(DF$cyl)

SSE <- list()
for (i in cms){
   SSE[[paste0("SE",i)]] <- subset(DF, DF$cyl == i)
}

#calling by names
for (i in names(SSE)){
   SSE[[i]] <- arrange(SSE[[i]], mpg)
   print(SSE[[i]])
}

Option 2

#using split function
SSE2 <- split(DF, DF$cyl)

#using lapply
SSE2 <- lapply(SSE2, function(x){
   x <- arrange(x, mpg)
   print(x)
})
  • Related