Arrays R中向量数组上的多变量函数
我想定义一个多变量函数,然后对向量数组进行操作,向量的元素就是变量的值。并且,将该数组替换为函数输出的数组。对于2变量版本,外部(或外部+矢量化)工作正常。但对于更高的维度,我似乎无法想出干净透明的东西 我将使用一个双变量(二维)示例,但我对一个不限于此的解决方案感兴趣 定义温度和时间等向量:Arrays R中向量数组上的多变量函数,arrays,r,function,variables,Arrays,R,Function,Variables,我想定义一个多变量函数,然后对向量数组进行操作,向量的元素就是变量的值。并且,将该数组替换为函数输出的数组。对于2变量版本,外部(或外部+矢量化)工作正常。但对于更高的维度,我似乎无法想出干净透明的东西 我将使用一个双变量(二维)示例,但我对一个不限于此的解决方案感兴趣 定义温度和时间等向量: temp=seq(10,50,10) time=seq(5,10,1) 这可用于使用expand.grid构建数组 arrayInput <- expand.grid(temp=seq(10,50
temp=seq(10,50,10)
time=seq(5,10,1)
这可用于使用expand.grid构建数组
arrayInput <- expand.grid(temp=seq(10,50,10), time=seq(5,10,1))
arrayInput您可以执行以下操作:
dim(matInput) <- c(5, 6, 2)
#or matInput <- array(matInput, dim = c(5, 6, 2))
func(matInput[,,1], matInput[,,2])
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 4.524187 5.429025 6.333862 7.238699 8.143537 9.048374
#[2,] 4.756147 5.707377 6.658606 7.609835 8.561065 9.512294
#[3,] 4.836081 5.803297 6.770513 7.737729 8.704945 9.672161
#[4,] 4.876550 5.851859 6.827169 7.802479 8.777789 9.753099
#[5,] 4.900993 5.881192 6.861391 7.841589 8.821788 9.801987
dim(matInput)一个不错的功能是outer
。我认为这可以计算出您想要的输出,尽管输入只是初始向量:outer(seq(10,50,10),seq(5,10,1),function(temp,time)time*exp(-1/temp))
谢谢,我在第一段中提到了outer,这很好,也许我可以将其扩展到更高维度的outer(outer()).有人在这里尝试了一个“multi.outer”函数:谢谢。我尝试使用data.frame:>dfInput dim(dfInput)来完全实现第一行中的功能
dim(matInput) <- c(5, 6, 2)
#or matInput <- array(matInput, dim = c(5, 6, 2))
func(matInput[,,1], matInput[,,2])
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 4.524187 5.429025 6.333862 7.238699 8.143537 9.048374
#[2,] 4.756147 5.707377 6.658606 7.609835 8.561065 9.512294
#[3,] 4.836081 5.803297 6.770513 7.737729 8.704945 9.672161
#[4,] 4.876550 5.851859 6.827169 7.802479 8.777789 9.753099
#[5,] 4.900993 5.881192 6.861391 7.841589 8.821788 9.801987