在R中使用expand.grid应用函数

时间:2014-08-24 21:34:14

标签: r map

我有两个向量xy。我使用以下函数创建一个网格:

v = expand.grid(x, y)

我有一个定义如下的函数

N <- function(a, b , dat){
     m = ncol(Filter(function(z) a*max(z)*min(z) < b , dat[1:ncol(dat)]))
     return(m)
}

然后我需要在N

的网格上最大化x,y
Maximize <- function(x , y ,dat){
          v = as.matrix(expand.grid(x,y))
          # Here is where I want to map the values of v and get the maximum element and 
          # get the tuple in v that maximized N
          temp1 <- max(apply(v , 1 , N(v[[1]] , v[[2]] , dat)))
}

由于

2 个答案:

答案 0 :(得分:4)

地图不会像这样迭代列表中的行。 <怎么样

x <- 1:3
y <- 11:13
v <- expand.grid(x, y)
do.call(mapply, c(function(a, b) a+b, unname(v)))
# [1] 12 13 14 13 14 15 14 15 16

此处每个值都作为单独的参数传递给函数。

答案 1 :(得分:1)

您可以使用apply

apply(v, 1, myfunction)

myfunction是你的职能(你在评论中澄清说它比仅仅添加更复杂)。 1表示您要应用于行(2意味着应用于列)。

如果xy都是数字(或两个字符向量)*,您当然希望先将v转换为矩阵:

apply(as.matrix(v), 1, myfunction)

这将更有效,并使值传递给myfunction一个向量而不是一行数据帧。

然而,如果myfunction的内容是某种数字操作,那么您很有可能将其矢量化。


*如果xy都是字符向量,请不要忘记在stringsAsFactors=FALSE来电中使用expand.grid

相关问题