1

is there an "apply" application for this instead of double-looping across each row of two data frames in base R (without using packages)?

listD <- matrix(1:6, ncol=2)
listD <- split(listD,seq(NROW(listD)))
df1 <- data.frame(x=c(1,2), y=c(3,4))
df2 <- data.frame(x=c(3,2), y=c(1,1))
testFunc <- function(a, b, c) a * (b + c)

for (j in 1:nrow(df1)) {
  for (s in 1:nrow(df2)) {
     print(lapply(listD, FUN= testFunc, b=df1[j,], c=df2[s,]))
  }
}

Thank you!

0

1 Answer 1

1

Use outer for its side effect:

invisible(outer(as.matrix(df1), as.matrix(df2), FUN = Vectorize(function (b, c) {
  print(lapply(listD, testFunc, b, c))
  NULL
})))

I don't know if this is an improvement on your for loop. There's a myth going round that for loops in R must be avoided at all costs (perhaps they look too easy?)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you dash2! I didn't know about outer! could you please explain why I would need "invisible" and "NULL" (if I don't use NULL I get an error)... also... how do I save this? thanks!!
You need it because otherwise it tries to print the result as a matrix, which it won't be. Saving the result is hard with outer because you can't return the result as a matrix. You might want to go inside out: put the lapply outside the outer call and return a list of matrices.
Ok if there is no difference between looping and apply then I will stick to looping as it's clearer (at least to me right now...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.