how to create 100 vectors in R in one go, and combine them all into one dataset

Dear R-community,

I have a list in my workspace named “sample_experiment”, from which I need to draw some information in the form of vectors, like this:

first_column <- sample_experiment[[1]]$latent

second_column <- sample_experiment[[2]]$latent

third_column <- sample_experiment[[3]]$latent

And so on, up to

hundred_column <- sample_experiment[[100]]$latent

Each vector (column) would contain 10 different numerical values.

The question is, could guys please suggest a code to create all 100 vectors (columns) in one go, as it is obviously unfeasible to manually type all 100 vectors? Also, could guys suggest a code to combine all created 100 vectors into a dataframe with 10 rows and 100 columns?

Thank you guys for your time and consideration in regard to this matter!

You can just feed this to dplyr::bind_cols.

library(dplyr)

# Creating some data that looks like your list
sample_experiment <- lapply(
    1:100,
    function(x) {
        list('latent' = runif(10))
    }
)

df <- bind_cols(sample_experiment)
#> New names:

df
#> # A tibble: 10 x 100
#>    latent...1 latent...2 latent...3 latent...4 latent...5 latent...6 latent...7
#>         <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
#>  1     0.781      0.184       0.123      0.945     0.0992     0.0220      0.333
#>  2     0.754      0.377       0.904      0.384     0.483      0.341       0.697
#>  3     0.123      0.0614      0.566      0.576     0.815      0.416       0.446
#>  4     0.738      0.827       0.728      0.161     0.507      0.881       0.105
#>  5     0.797      0.357       0.309      0.368     0.886      0.399       0.313
#>  6     0.264      0.404       0.231      0.306     0.666      0.171       0.421
#>  7     0.749      0.0410      0.335      0.897     0.959      0.0109      0.315
#>  8     0.810      0.331       0.813      0.971     0.830      0.710       0.998
#>  9     0.825      0.147       0.981      0.604     0.502      0.273       0.807
#> 10     0.0575     0.980       0.992      0.602     0.946      0.382       0.522
#> # ... with 93 more variables: latent...8 <dbl>, latent...9 <dbl>...

Created on 2022-05-13 by the reprex package (v1.0.0)

2 Likes

Thank you for a quick and really helpful reply!)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.