我有一个矩阵,如:
A
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
每行中要限制的元素数量向量(其他元素将变换为0)。
c
[1] 2 3
我想获得(尽可能至少循环):
B
[,1] [,2] [,3] [,4]
[1,] 1 3 0 0
[2,] 2 4 6 0
答案 0 :(得分:0)
m <- matrix(1:8, nrow = 2)
sel <- 2:3
#create a integer matrix of col numbers
#use this to create a logical matrix indicating
#if the col numbers are greater than the threshold
#this relies on vector recycling
subs <- col(m) > sel
#assign to subset
m[subs] <- 0
# [,1] [,2] [,3] [,4]
#[1,] 1 3 0 0
#[2,] 2 4 6 0