在每行中找到前n个正列并在R中创建新矩阵

问题描述 投票:0回答:1

我在 R 中有一个 5x5 矩阵,我想知道如何选择每行中的前 2 个正列。假设我的矩阵是:

x_mat = matrix(rnorm(25),nrow=5)

看起来像这样:

        [,1]       [,2]        [,3]       [,4]       [,5]
[1,]  0.4530790 -0.6345827 -0.09875488 -2.1310380  1.2052932
[2,]  0.8857939  1.7273651 -1.66136354  1.2525782  1.3527161
[3,] -0.2236681  0.2938106  0.45233337  0.4916921  1.0909765
[4,]  1.5959947 -0.9065362 -0.78020171 -1.0510121 0.8550553
[5,]  0.1472118  0.7305333  0.87001933 -2.0218497 -0.7610662

如何选择每行中的前两个正列,以便我的矩阵如下所示:

        [,1]       [,2]       
[1,]  0.4530790  1.2052932
[2,]  0.8857939  1.7273651 
[3,]  0.2938106  0.45233337  
[4,]  1.5959947  0.8550553
[5,]  0.1472118  0.7305333  
r matrix lapply
1个回答
0
投票
apply(x_mat, 1, \(x) x[x > 0][1:2])
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 0.9881999 0.1714773 0.7963736 0.5237629 0.2454426
[2,]        NA        NA 0.5453892 0.0186712 1.4366101
© www.soinside.com 2019 - 2024. All rights reserved.