【问题标题】:Limit the number of elements in each row of matrix限制矩阵每行的元素个数
【发布时间】:2015-08-21 10:25:22
【问题描述】:

我有一个像这样的矩阵:

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

【问题讨论】:

    标签: r matrix vector element


    【解决方案1】:
    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
    

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多