提问人:cliu 提问时间:1/25/2022 更新时间:1/25/2022 访问量:30
基于另一个列表中的数字的矩阵列表的示例行
Sample rows of a list of matrices based on numbers from another list
问:
我有一个矩阵列表,我想根据另一个列表的数字从中随机抽取行。以下是矩阵列表:
x <- list(`1` = matrix(1:20, nrow=10), `2` = matrix(1:20, nrow=10))
这是数字列表
y <- list(`1` = 2, `2` = 3) #for `1` I want to draw 2 rows and for `2` I want to draw 3 rows
最终列表将如下所示:
$`1`
[,1] [,2]
[1,] 1 11
[2,] 6 16
$`1`
[,1] [,2]
[1,] 1 11
[2,] 7 17
[3,] 9 19
如何在 R 基础中实现这一目标?感谢您的帮助!
答:
1赞
akrun
1/25/2022
#1
我们可以在 'x' 和 'y' 的相应元素上使用 - 循环,根据 'y' 中的值对 'x' 中的 es 行进行采样Map
base R
list
matrix
Map(function(u, v) u[sample(seq_len(nrow(u)), v),], x, y)
$`1`
[,1] [,2]
[1,] 9 19
[2,] 6 16
$`2`
[,1] [,2]
[1,] 3 13
[2,] 8 18
[3,] 5 15
或从map2
purrr
library(purrr)
map2(x, y, ~ .x[sample(seq_len(nrow(.x)), .y), ])
如果我们转换为 ,那么也可以使用tibble
slice_sample
library(dplyr)
library(tibble)
map2(x, y, ~ .x %>%
as.data.frame %>%
as_tibble %>%
slice_sample(n = .y))
$`1`
# A tibble: 2 × 2
V1 V2
<int> <int>
1 4 14
2 7 17
$`2`
# A tibble: 3 × 2
V1 V2
<int> <int>
1 8 18
2 6 16
3 9 19
评论
y<-list(`2` =3)
x