-1

I have 2 lists of matrices A and B:

n<-10
generate<-function (n){
matrix(runif(10*10),ncol = 10) 
}
A<-lapply(1:n, generate)
B<-lapply(1:n, generate)

I am trying to use lapply to run it through a function with two inputs. Where my function is a function I have createdABC():

ABC(x,y)

I now try to run the lists A for x and B for y by using lapply:

l<-lapply(A,B, ABC(x,y))

This does not work as it recognises B as a function instead of a list that should be associated with y. Do I need to use sapply or mapplyand if so how?

Any help would be appreciated, thanks.

adaodante
  • 63
  • 2
  • 7
  • 1
    What happened when you tried `mapply`? – Rich Scriven Aug 25 '16 at 16:25
  • Your function `generate` takes `n` as an input, but it does not use `n` anywhere in the function. – bouncyball Aug 25 '16 at 16:28
  • @Dirty Sock Sniffer when using `mapply` I get the following `Error in get(as.character(FUN), mode = "function", envir = envir) : object 'b' of mode 'function' was not found`. @bouncyball that is not my problem it is the lapply bit. – adaodante Aug 25 '16 at 16:36
  • 1
    @adaodante `mapply(x = A, y = B, FUN = function(x, y) ABC(x, y))` – bouncyball Aug 25 '16 at 16:41
  • @bouncyball thank you the `mapply(x = A, y = B, FUN = function(x, y) ABC(x, y))` has worked thanks again. – adaodante Aug 25 '16 at 16:47
  • @adaodante see [this post](http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega?rq=1) for more information on the `*apply` family of functions – bouncyball Aug 25 '16 at 16:51
  • @bouncyball `FUN = function(x, y) ABC(x, y)` is doubly redundant. Simply write `FUN = ABC`. Furthermore, the function is the first parameter in `mapply`, so you can simply write `mapply(ABC, A, B)`. – Konrad Rudolph Aug 25 '16 at 16:59
  • I’m not sure what you want to achieve but the code that you’ve written can be shortened drastically by using `replicate(10, matrix(runif(10*10),ncol = 10))`. This replaces the first four lines of your script. You can use it twice to generate `A` and `B`. – Konrad Rudolph Aug 25 '16 at 17:00

1 Answers1

-1

mapply is what you looking for?

n<-10
generate<-function (n){
  matrix(runif(10*10),ncol = 10) 
}
A<-lapply(1:n, generate)
B<-lapply(1:n, generate)


mapply(generate, c( 1:n,1:n))
USER_1
  • 2,409
  • 1
  • 28
  • 28