R 限制矩阵每行中的元素数

R 限制矩阵每行中的元素数,r,matrix,vector,element,R,Matrix,Vector,Element,我有一个矩阵,比如: A [,1] [,2] [,3] [,4] [1,] 1 3 5 7 [2,] 2 4 6 8 以及每行中要限制的元素数的向量(其他元素将转换为0) 我希望获得(至少尽可能使用循环): m c [1] 2 3 B [,1] [,2] [,3] [,4] [1,] 1 3 0 0 [2,] 2 4 6 0 m <- matrix(1:8, nrow

我有一个矩阵,比如:

A
     [,1] [,2] [,3] [,4]
[1,]    1    3    5    7
[2,]    2    4    6    8
以及每行中要限制的元素数的向量(其他元素将转换为0)

我希望获得(至少尽可能使用循环):

m
 c
[1] 2 3
B
     [,1] [,2] [,3] [,4]
[1,]    1    3    0    0
[2,]    2    4    6    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