tjebo
tjebo

Reputation: 23767

Sample generation: Make list of data frames for each combination of list of vectors

For testing purposes, I would like to automate sample generation. In the end, this should result in a list of data frames that have one fixed id column and two variable columns that can have multiple combinations.

Although I have a solution (see below), I feel that there may be a more educated way of achieving this.

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

Created on 2020-05-19 by the reprex package (v0.3.0)

Upvotes: 2

Views: 49

Answers (1)

lroha
lroha

Reputation: 34601

You could use combn() on the eye vector and use its function argument to index the sample dataframe:

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

Upvotes: 2

Related Questions