3

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.

B--rian
  • 5,578
  • 10
  • 38
  • 89
Quest
  • 53
  • 2
  • 8
  • Possible duplicate of [Grouping functions (tapply, by, aggregate) and the \*apply family](https://stackoverflow.com/questions/3505701/grouping-functions-tapply-by-aggregate-and-the-apply-family) – Bruna w Aug 08 '19 at 17:06
  • It's not working because you have three `a` in your code each of them playing a different role. Use other names. – Rui Barradas Aug 08 '19 at 17:14
  • `result <- lapply(list(A,B,C,D), function(DF) { func(a, b, c, DF) })` – Rui Barradas Aug 08 '19 at 17:16

1 Answers1

2

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!

Jeffrey Brabec
  • 481
  • 6
  • 11
  • 1
    No the whole point of writing for loop is to avoid repeatative steps . Already A,B,C,D are dataframes – Quest Aug 08 '19 at 18:14
  • I want the same dataframe name as that I pass in 4th parameter – Quest Aug 08 '19 at 18:15
  • Sorry I should have been clearer in my explanation. I think I complicated my answer by adding the data frame creation. Those are just supposed to represent your data frames. This for loop as I've written should pass each data frame to the fourth position iteratively like you want. – Jeffrey Brabec Aug 08 '19 at 18:20
  • Oh okay yes gotcha but I want the name 'result' same as that of the df name – Quest Aug 08 '19 at 18:27
  • Got it. You could try making 'result' a list containing each data frame's result from the function `result <- list()` After the loop runs you might just need to change the names of each member of the list by using `names(result) <- c("A", "B", "C", "D")` – Jeffrey Brabec Aug 08 '19 at 18:29