从 R 中的列表中采样 n 个元素
Sample n elements from a list in R
假设我在 R 中有一个这样的列表:
myList
[[1]]
[1] 4 6 7 9
[[2]]
[1] 1 2 3 6 9 10
[[3]]
[1] 12 41 2 8 22 6 16
我想从整个列表中获取 n(例如 5)个样本,如下所示:
sampledList
[[1]]
[1] 4 9
[[2]]
[1] 1 10
[[3]]
[1] 22
有什么直接的解决方案吗?
由于我们需要对所有元素立即执行此操作,因此一个选项是将 list
转换为两列 data.frame 和 stack
- 将 [=12= 命名为]元素与列表的顺序,和stack
。然后通过指定 n
、split
序列列 'ind' 和 unname
的采样子集(如有必要)来使用 slice_sample
。
library(dplyr)
n1 <- 5
stack(setNames(myList, seq_along(myList))) %>%
slice_sample(n = n1) %>%
{split(.$values, .$ind)} %>%
unname
数据
myList <- list(c(4, 6, 7, 9), c(1, 2, 3, 6, 9, 10), c(12, 41, 2, 8, 22,
6, 16))
这是基本的 R 方式。
set.seed(2021)
sampledList <- lapply(seq_along(myList), function(i) {
setNames(myList[[i]], paste(i, seq_along(myList[[i]]), sep = "."))
})
sampledList <- sample(unlist(sampledList), 5)
split(unname(sampledList), sub("\..*", "", names(sampledList)))
#$`2`
#[1] 3 2 10
#
#$`3`
#[1] 8 16
上面的代码作为一个函数:
fun <- function(x, n = 5){
y <- lapply(seq_along(x), function(i) {
setNames(x[[i]], paste(i, seq_along(x[[i]]), sep = "."))
})
y <- sample(unlist(y), 5)
split(unname(y), sub("\..*", "", names(y)))
}
fun(myList)
假设我在 R 中有一个这样的列表:
myList
[[1]]
[1] 4 6 7 9
[[2]]
[1] 1 2 3 6 9 10
[[3]]
[1] 12 41 2 8 22 6 16
我想从整个列表中获取 n(例如 5)个样本,如下所示:
sampledList
[[1]]
[1] 4 9
[[2]]
[1] 1 10
[[3]]
[1] 22
有什么直接的解决方案吗?
由于我们需要对所有元素立即执行此操作,因此一个选项是将 list
转换为两列 data.frame 和 stack
- 将 [=12= 命名为]元素与列表的顺序,和stack
。然后通过指定 n
、split
序列列 'ind' 和 unname
的采样子集(如有必要)来使用 slice_sample
。
library(dplyr)
n1 <- 5
stack(setNames(myList, seq_along(myList))) %>%
slice_sample(n = n1) %>%
{split(.$values, .$ind)} %>%
unname
数据
myList <- list(c(4, 6, 7, 9), c(1, 2, 3, 6, 9, 10), c(12, 41, 2, 8, 22,
6, 16))
这是基本的 R 方式。
set.seed(2021)
sampledList <- lapply(seq_along(myList), function(i) {
setNames(myList[[i]], paste(i, seq_along(myList[[i]]), sep = "."))
})
sampledList <- sample(unlist(sampledList), 5)
split(unname(sampledList), sub("\..*", "", names(sampledList)))
#$`2`
#[1] 3 2 10
#
#$`3`
#[1] 8 16
上面的代码作为一个函数:
fun <- function(x, n = 5){
y <- lapply(seq_along(x), function(i) {
setNames(x[[i]], paste(i, seq_along(x[[i]]), sep = "."))
})
y <- sample(unlist(y), 5)
split(unname(y), sub("\..*", "", names(y)))
}
fun(myList)