我在R中构造了一个两个变量整数值函数f(x,y)
,它只为单个条目(不是例如f(1,1:5)
)定义良好。我正在有效地寻找一个整数值函数F(x,y,z,w)
,它将给出输出:
f(x,y),f(x,y+1),...,f(x,w),f(x+1,y),f(x+1,y+1),...,f(x+1,w),...,f(z,y),f(z,y+1),...,f(z,w)
作为(z-x+1) by (w-y+1)
矩阵。欢呼任何帮助!
答案 0 :(得分:1)
outer
似乎就是你在这里寻找的。 p>
# make a simple function
f <- function(x, y){x+y}
x <- 3
z <- 5
y <- 2
w <- 7
outer(x:z, y:w, f)
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 5 6 7 8 9 10
#[2,] 6 7 8 9 10 11
#[3,] 7 8 9 10 11 12
如果您的函数确实只能将标量作为输入,那么您可能需要使用Vectorize
来使此方法有效
# Function that can only takes scalars...
f <- function(x, y){if(length(x) > 1 | length(y) > 1) stop('blah'); x + y}
outer(x:z, y:w, f)
#Error in FUN(X, Y, ...) : blah
myvectorizedfun <- Vectorize(f)
outer(x:z, y:w, myvectorizedfun)
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 5 6 7 8 9 10
#[2,] 6 7 8 9 10 11
#[3,] 7 8 9 10 11 12
答案 1 :(得分:-1)
我发现for
循环是处理矩阵创建的最简单方法。这是您尝试做的基本概要:
F <- function(x,y,z,w) {
Matrix <- matrix(nrow=z-x, ncol=w-y) # Set dimensions of your matrix
for(i in 1:(z-x)){ # Summing over all x
for (j in 1:(w-y)){ # Summing over all y
Matrix[i,j] <- f(i+x,j+y) # Evaluate and store in matrix
}}
Matrix <<- Matrix # Assign Matrix outside the function F
}