如何转置列表的每个向量,为它们分配一个唯一的编号,并将它们绑定在 r 中



我有以下列表,并希望创建一个包含每个列表(有很多(的data.frame。这里有一个例子:

v11 <- c("was_on_the_moon", "safe", "best", "super")
v22 <- c("no", "yes", "three", "four")
dat1 <- data.frame(cbind(v11, v22))
v11 <- c("was_on_the_moon", "safe", "best", "super")
v22 <- c("no", "yes", "three", "four")
dat2 <- data.frame(cbind(v11, v22))
list_first <- list(dat1, dat2)

结果应如下所示:

  was_on_the_moon safe   best super 
1 yes              yes  three  four
2 no              sure  check  four

tidyverse解决方案:

map(list_first, ~ setNames(., c("var", "val"))) %>%
  bind_rows(.id = "id") %>%
  spread(var, val)
a <- unlist(myfiles, recursive = FALSE)
names <- a$V1
t(sapply(myfiles, function(x) setNames(x$V11, names)[match(names, x$V22)]))

最新更新