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?
CodePudding user response:
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)))
CodePudding user response:
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 <- cbind.data.frame(
sample_experiment
)
names(all) <- 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
CodePudding user response:
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)
)