样本生成:为矢量列表的每个组合制作数据框列表

  • 本文关键字:列表 组合 数据 样本 r
  • 更新时间 :
  • 英文 :


出于测试目的,我想自动生成样本。最后,这应该会产生一个数据框列表,这些数据框具有一个固定 id 列和两个可以有多个组合的变量列。

虽然我有一个解决方案(见下文(,但我觉得可能有更受教育的方法来实现这一点。

set.seed(42)
id <- sample(letters[1:20])
# using data frame for cbind later - may there a way to use the matrix instead?
df_sample <- as.data.frame(replicate(6, sample(30:40, size = 20, replace = T)))
eye <- c("r", "l", "re", "le", "od", "os")
colnames(df_sample) <- eye
# This is how I generate the combinations - there might be a more elegant way too
mx_comb <- gtools::combinations(v = eye, r = 2, n = length(eye))
# maybe there is a different way than the for loop, e.g. with apply on a matrix?
ls_eye <- list()
for (i in 1:nrow(mx_comb)) {
ls_eye[[i]] <- cbind(id, df_sample[mx_comb[i, 2]], df_sample[mx_comb[i, 1]])
}
lapply(ls_eye[1:2], head, 2)
#> [[1]]
#>   id le  l
#> 1  q 35 31
#> 2  e 31 34
#> 
#> [[2]]
#>   id od  l
#> 1  q 32 31
#> 2  e 35 34

创建于 2020-05-19 由 reprex 软件包 (v0.3.0(

您可以在眼向量上使用combn(),并使用其函数参数为示例数据帧编制索引:

df_sample <- cbind(id, df_sample)
res <- combn(eye, 2, FUN = function(x) df_sample[c("id", x)] , simplify = FALSE)

最新更新