简体   繁体   中英

How can I transpose each vectors of a list assign a unique number to them, and bind them in r?

I have following list and would like to create a data.frame with each of the lists (there are many) combined. Here an example:

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)

The result should be as follows:

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

A tidyverse solution:

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)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM