Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 459
Quest Avatar asked Oct 26 '25 15:10

Quest


1 Answers

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!

like image 50
Jeffrey Brabec Avatar answered Oct 29 '25 04:10

Jeffrey Brabec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!