大洼村二号机 发表于 2017-2-8 09:19 
完!美!试了一下果然是可行的!
不过不太懂这么写的意思,outer在这里的用法是相当于新建了一个函数d, ...
Help on "outer" function:
Description
The outer product of the arrays X and Y is the array A with dimension c(dim(X), dim(Y)) where element A[c(arrayindex.x, arrayindex.y)] = FUN(X[arrayindex.x], Y[arrayindex.y], ...).
Usage
outer(X, Y, FUN = "*", ...)
Basically it just creates all possible combinations of two vectors (denoted "X" and "Y" above) and call the *binary* function (denoted "FUN" above) on each and every of the combination.
But as we have a 3-argument function here I just loop through the 3rd dimension using "lapply". In "lapply", for each value "d" in vector "B" we find all possible combinations of the elements in vectors C and R call the function with one of the combinations and "d".
For cases with more than 3 dimensions, you can certainly just put another or several other "lappy" outside the code. But I would not recommend that. If you have a similar question but in much higher dimension and it is fine to have results stored in a 2-d table, perhaps the following code is more clear (back to my original suggestion of using "mapply"):
- # Suppose we have a four-argument function: myfun <- function(w, x, y, z)
- # And we have four vectors: A, B, C, D from whose values should be passed to arguments w, x, y, and z, respectively.
- # Create a data.frame for all combinations of elements in A, B, C and D
- mydf <- Reduce( merge, list( data.frame(A = A), data.frame(B = B), data.frame(C = C), data.frame(D = D) ) )
- mydf$res <- with( mydf, mapply( myfun, w = A, x = B, y = C, z = D ) )
复制代码The code was not tested though. Let me know if you have any issues running it.