使用R中的另一个列表从列表中对行进行子集化

时间:2018-01-07 14:52:10

标签: r subset lapply

我正在尝试使用R来列出列表中的行数。

我有2个列表,一个包含n行和p列的矩阵,第二个列表包含我需要子集的行数。

mat <- list(a = matrix(rnorm(8*4),8), b = matrix(rnorm(15*4),15), c = matrix(rnorm(7*4),7))
rw <- list(a = 6, b = 7, c = 4)

两个列表都有通用名称,在上面的例子中,我想保留元素前6行,b前7行和c 4行。

你会如何在R

中做到这一点

1 个答案:

答案 0 :(得分:4)

Map的一个解决方案:

Map(function(x, y) x[1:y, ], mat, rw)

# $a
# [,1]       [,2]       [,3]       [,4]
# [1,] 1.3331549 -0.6985623 -1.1842788 -0.1496880
# [2,] 0.2096395 -0.2901906  0.4210395  0.9116542
# [3,] 0.1763317  1.3858205 -1.1567526 -1.1794618
# [4,] 1.3596395  0.5815012 -0.3681799 -0.6569447
# [5,] 0.2251352  0.2331387 -1.2509844 -1.1346729
# [6,] 0.6796729  1.1274772  0.3992489  0.2305927
# 
# $b
# [,1]       [,2]       [,3]       [,4]
# [1,]  0.30700748 -1.2173855 -0.3377885 -0.6748974
# [2,]  1.09506443 -0.6142685 -1.1301122 -0.7792081
# [3,] -0.61049306 -1.3414474  0.9771373  1.0191636
# [4,]  0.66687294 -0.5269721  0.9971987 -0.6514121
# [5,]  0.54623236  0.9020964  0.3252700 -0.3925129
# [6,] -0.04848903 -0.5204047  0.3344675 -0.3232105
# [7,] -0.56502719 -0.3743275  2.1760364 -0.2941956
# 
# $c
# [,1]        [,2]      [,3]       [,4]
# [1,] -0.3225609 -0.40126955 -1.787255 -1.5005721
# [2,]  0.3474430 -1.16657015  1.106033  0.3114282
# [3,]  0.4099467 -0.04353555  0.838330  0.3282246
# [4,] -1.4648740  0.51279791  0.198768 -0.3394502