矩阵到矢量最小比较而不使用在R中的apply

时间:2015-09-17 20:12:55

标签: r function vector vectorization apply

我正在尝试创建一个接收矩阵M和向量v的函数。然后,它应该在Mv的列之间采用元素最小值。因此,M = length(v)

的行数

例如,下面是两个相等长度的矢量。与矢量相比,我希望它适用于矩阵。

vectorelementwisemin = function(x,y){   #x is a vector, y is a vector (same length)


            ind = which(x > y)
            z = x
            z[ind] <- y[ind]  

            return(z)
}

例如,矢量化函数可以包含:

    M
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]    0    0    0    0    0    0    0    0    0     0     0     0
[2,]    2    2    5    4    2    3    4    1    4     4     4     2
[3,]    0    0    0    0    0    0    0    0    0     0     0     0
[4,]    0    0    0    0    0    0    0    0    0     0     0     0
[5,]    0    6    0    0    0    0    0    0    0     0     0     0
[6,]    0    0    0    0    0    0    0    0    0     0     0     0

    v

     0      4      2      1      3      0

And return 

    minmat(M,v)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]    0    0    0    0    0    0    0    0    0     0     0     0
[2,]    2    2    4    4    2    3    4    1    4     4     4     2
[3,]    0    0    0    0    0    0    0    0    0     0     0     0
[4,]    0    0    0    0    0    0    0    0    0     0     0     0
[5,]    0    3    0    0    0    0    0    0    0     0     0     0
[6,]    0    0    0    0    0    0    0    0    0     0     0     0

1 个答案:

答案 0 :(得分:2)

您可以使用minmat <- function(M, v) pmin(M, v),但您可能希望添加if (nrow(M) != length(v)) stop("")

之类的内容