向量化矩阵行中的操作
Vectorizing which operation across the rows of a matrix
我想对矩阵 X
上的 which
操作进行矢量化 (apply
),如下面的 for
循环所示,结果为矢量 ind
:
X = matrix( 1:20, 4, 5 )
V = sample( 1:20, 4 )
ind = numeric()
for( i in 1:nrow(X) ) ind[i] = max( c(0, which(X[i,] < V[i]) ))
操作returns in ind
for each row in X
the index of the element with the highest value smaller by the value by the X
-row -V
.
的对应元素
操作max
将所有符合条件的索引的向量映射到一个标量。或者,我会对返回的操作感到满意,例如所有索引的 list
(我可以 lapply
max
)。
这是一个简单的lapply示例
X = matrix( 1:20, 4, 5 )
V = sample( 1:20, 4 )
ind = numeric()
for( i in 1:nrow(X) ) ind[i] = max( c(0, which(X[i,] < V[i]) ))
mymax = function(matrix, sample) {
whichlist = which(matrix < sample)
max(0, whichlist)
}
ind2 = unlist(lapply(1:nrow(X), function(r) mymax(X[r,], V[r])))
identical(ind, ind2)
# [1] TRUE
这是另一个答案,您首先 sweep
向量 V
跨越 X
的每一行,然后使用 apply 确定每个行的最大 TRUE
元素行。
set.seed(14)
X = matrix( 1:20, 4, 5 )
V = sample( 1:20, 4 )
ind1 = numeric()
for( i in 1:nrow(X) ) ind1[i] = max(c(0, which(X[i,] < V[i]) ))
ind2 <- apply(
sweep(X, 1, V, "<"),
1,
function(x){
max(
which(
x,
arr.ind = TRUE)
)
}
)
> ind1
[1] 2 5 2 4
> ind2
[1] 2 5 2 4
如果你的矩阵像你分享的例子一样增加值(我当然怀疑),但如果是这样你可以简单地做,
rowSums(X < V)
#[1] 4 3 4 0
然而,如果不是这种情况,那么一个简单的 apply
就足够了,即
apply(X < V, 1, function(i)max(which(i)))
#[1] 4 3 4 -Inf
请记住,所有数学运算都是向量化的,因此 <
是向量化的
你可以照常替换-Inf
apply(
(X < V) * X
, 1
, which.max
)
我想对矩阵 X
上的 which
操作进行矢量化 (apply
),如下面的 for
循环所示,结果为矢量 ind
:
X = matrix( 1:20, 4, 5 )
V = sample( 1:20, 4 )
ind = numeric()
for( i in 1:nrow(X) ) ind[i] = max( c(0, which(X[i,] < V[i]) ))
操作returns in ind
for each row in X
the index of the element with the highest value smaller by the value by the X
-row -V
.
操作max
将所有符合条件的索引的向量映射到一个标量。或者,我会对返回的操作感到满意,例如所有索引的 list
(我可以 lapply
max
)。
这是一个简单的lapply示例
X = matrix( 1:20, 4, 5 )
V = sample( 1:20, 4 )
ind = numeric()
for( i in 1:nrow(X) ) ind[i] = max( c(0, which(X[i,] < V[i]) ))
mymax = function(matrix, sample) {
whichlist = which(matrix < sample)
max(0, whichlist)
}
ind2 = unlist(lapply(1:nrow(X), function(r) mymax(X[r,], V[r])))
identical(ind, ind2)
# [1] TRUE
这是另一个答案,您首先 sweep
向量 V
跨越 X
的每一行,然后使用 apply 确定每个行的最大 TRUE
元素行。
set.seed(14)
X = matrix( 1:20, 4, 5 )
V = sample( 1:20, 4 )
ind1 = numeric()
for( i in 1:nrow(X) ) ind1[i] = max(c(0, which(X[i,] < V[i]) ))
ind2 <- apply(
sweep(X, 1, V, "<"),
1,
function(x){
max(
which(
x,
arr.ind = TRUE)
)
}
)
> ind1
[1] 2 5 2 4
> ind2
[1] 2 5 2 4
如果你的矩阵像你分享的例子一样增加值(我当然怀疑),但如果是这样你可以简单地做,
rowSums(X < V)
#[1] 4 3 4 0
然而,如果不是这种情况,那么一个简单的 apply
就足够了,即
apply(X < V, 1, function(i)max(which(i)))
#[1] 4 3 4 -Inf
请记住,所有数学运算都是向量化的,因此 <
是向量化的
你可以照常替换-Inf
apply(
(X < V) * X
, 1
, which.max
)