出于测试目的,我想自动生成示例。最后,这应该会生成一个数据框列表,其中包含一个固定 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
由 reprex package 于 2020-05-19 创建(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/