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

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, to suggest a code to create all 100 vectors (columns) in one go, as it is obviously unfeasible to manually type all 100 vectors? Also, to combine all created 100 vectors into a dataframe with 10 rows and 100 columns?

r


Solution 1:[1]

I am making a bit of an assumption on your data format, but perhaps this will work using purrr.

sample_experiment <- replicate(100, list(data.frame(latent = runif(10))))

library(purrr)

sample_experiment %>% 
  set_names(~ paste0("column_", seq_along(.))) %>% 
  map_dfc( "latent")

You can also make use of base R.

as.data.frame(lapply(sample_experiment, `[[`, "latent"),
              col.names = paste0("column_", seq_along(sample_experiment)))

Solution 2:[2]

This should work for you, if your columns can be called column_N:

sample_experiment <- list(
  data.frame(latent = c(1:10)),
  data.frame(latent = c(11:20)),
  data.frame(latent = c(21:30))
)

names_vec <- paste0("column_", 1:3)

all <- setNames(cbind.data.frame(lapply(sample_experiment, function(x) x[['latent']])), names_vec)

# tidyverse approach
library(tidyverse)

all <- map_dfc(sample_experiment, ~.x %>% select('latent')) %>% 
  set_names(nm = names_vec)

For this example, it returns:

   column_1 column_2 column_3
1         1       11       21
2         2       12       22
3         3       13       23
4         4       14       24
5         5       15       25
6         6       16       26
7         7       17       27
8         8       18       28
9         9       19       29
10       10       20       30

Solution 3:[3]

do.call(cbind, lapply(1:100, \(i) sample_experiment[[i]]$latent))

If you want the output as a frame with named columns ("col1", "col2"..etc), just wrap the above in setNames(as.data.frame()), as below:

setNames(
    as.data.frame(do.call(cbind, lapply(1:100, \(i) sample_experiment[[i]]$latent))),
    paste0("col",1:100)
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3