我正在尝试创建一个接收矩阵M
和向量v
的函数。然后,它应该在M
和v
的列之间采用元素最小值。因此,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
答案 0 :(得分:2)
您可以使用minmat <- function(M, v) pmin(M, v)
,但您可能希望添加if (nrow(M) != length(v)) stop("")