gpt4 book ai didi

r - 样本生成 : Make list of data frames for each combination of list of vectors

转载 作者:行者123 更新时间:2023-12-04 09:57:44 27 4
gpt4 key购买 nike

出于测试目的,我想自动生成样本。最后,这应该会生成一个数据框列表,其中包含一个固定的 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 package (v0.3.0)

最佳答案

您可以使用 combn()在眼睛向量上并使用其函数参数来索引样本数据帧:

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

关于r - 样本生成 : Make list of data frames for each combination of list of vectors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61888225/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com