Loop over Multiple Dataframes in a for Loop in R

Loop over Multiple Dataframes in a for Loop in R

I have four dataframes A,B,C,D. I want to iterate over these four dataframes so that each of them is passed to the custom function testdf() as the fourth parameter which can take only dataframe data type.

for (a in 1: (A,B,C,D)){
  a<-testdf(x,y,z,A)
}

I also tried using list but that didn't seem to work as even when I passed as.data.frame(mylist(A)) in the function it threw an error that list can't be passed.

3

1 Answer

The way you have your code written it seems like there are variable mix -ups. My example below should address that.

Using a list like you tried previously might be a good option.


A <- as.data.frame(0,matrix(0, nrow = 4, ncols = 6)
B <- as.data.frame(0,matrix(0, nrow = 5, ncols = 6)
C <- as.data.frame(0,matrix(0, nrow = 4, ncols = 4)
D <- as.data.frame(0,matrix(0, nrow = 3, ncols = 5)

list.dfs <- list(A,B,C,D)

for (i in 1:length(list.dfs)){

#Since I don't know your function I just catenated the letters with
#whatever is in your data frames
  result <- cat("a","b","c",i)

}

Let me know if that helps any or if you need clarification!

5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.