I have two lists, A and B:
List A contains K character vectors of length W. Each vector contains the same W string values but the indices of the strings may differ. We can think of this list in practice as containing vector of variable names, where each vector contains the same variable names but in potentially-differing orders..
List B contains K character vectors of length W. Each vector can contain W arbitrary values. We can think of this list in practice as containing vectors with the corresponding values of the variables contained in each vector of List A.
I am trying to generate a data frame that is K rows long and W rows wide, where the column names are the W unique values in each vector in List A and the values for each row are drawn from the vector found in that row's index in List B.
I've been able to do this (minimal working example below) but it seems very hackish because it basically involves turning the two lists into data frames and then assigning values from one as column names for the other in a loop.
Is there a way to skip the steps of turning each list into a data frame before then using a loop to combine them? Looping through the lists seems inefficient, as does generating the two data frames rather than a single data frame that draws on contents of both lists.
# Declare number of rows and columns
K <- 10
W <- 5
colnames_set <- sample(LETTERS, W)
# Generate example data
# List A: column names
list_a <- vector(mode = "list", length = K)
list_a <- lapply(list_a, function(x) x <- sample(colnames_set, W))
# List B: values
list_b <- vector(mode = "list", length = K)
list_b <- lapply(list_b, function(x) x <- rnorm(n = W))
# Define function to take a vector and turn it into a
# data frame where each element of the vector is
# assigned to its own colun
vec2df <- function(x) {
x %>%
as.data.frame(., stringsAsFactors = FALSE) %>%
t() %>%
as.data.frame(., stringsAsFactors = FALSE)
}
# Convert vectors to data frames
vars <- lapply(list_a, vec2df)
vals <- lapply(list_b, vec2df)
# Combine the data frames into one
# (note the looping)
for(i in 1:K){
colnames(vals[[i]]) <- vars[[i]][1, ]
}
# Combine rows into a single data frame
out <- vals %>%
dplyr::bind_rows()
rownames(out) <- NULL
# Show output
out