R:从值列表和变量名称列表创建数据框

R: Creating data frame from list of values and list of variable names

我有两个列表,A 和 B:

我正在尝试生成一个长 K 行、宽 W 行的数据框,其中列名是列表 A 中每个向量中的 W 个唯一值,每行的值都是从找到的向量中提取的在列表 B 中该行的索引中。

我已经能够做到这一点(下面的最小工作示例)但它看起来很老套,因为它基本上涉及将两个列表转换为数据框,然后在一个循环中将一个列表的值作为列名分配给另一个列表.

有没有办法跳过将每个列表转换为数据框的步骤,然后再使用循环将它们组合起来?遍历列表似乎效率低下,生成两个数据框而不是一个利用两个列表内容的数据框也是如此。

# 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

排列list_b中的数据,使变量对齐。我们可以使用 Map/mapply 来执行此操作,将输出转换为数据框并命名列。

setNames(data.frame(t(mapply(function(x, y) y[order(x)], list_a, list_b))), 
                     sort(colnames_set))