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

标签 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

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/

相关文章:

r - 匹配单词串并返回不匹配的单词

r - 将二进制向量转换为二进制矩阵

R - 如何将多个直方图绘制在一起?

r - 如何在不覆盖当前变量的情况下获取 R 代码?

r - R 中预测的预处理比例 - 没有获得相同的预测比例

r - 使用 ggplot2 手动着色置信区间

R 循环函数参数以将变量添加到数据框

R 编译错误的 RGL 包

重复滚动连接而不循环

r - XPath在R中的br标签之后提取文本