将命名的表列表转换为data.frame

时间:2017-02-27 14:31:58

标签: r dataframe tidyverse

我有list table这样的名字:

# make this simple and reproducible
set.seed(1)
days <- c("mon", "tue", "wed", "thu", "fri", "sat", "sun")

# create list of tables
mylist <- list(
  one = table(sample(days, 3, replace = TRUE)),
  two = table(sample(days, 5, replace = TRUE)),
  three = table(NULL),
  four = table(sample(days, 4, replace = TRUE))
)

    mylist
#$one
#
#fri tue wed 
#  1   1   1 
#
#$two
#
#fri sun tue 
#  1   3   1 
#
#$three
#< table of extent 0 >
#
#$four
#
#fri mon tue 
#  1   1   2 

我想将其转换为data.frame,其中所有原始列表元素都是结果data.frame中的行:

mydf
#      mon tue wed fri sun
#one     0   1   1   1   0
#two     0   1   0   1   3
#three   0   0   0   0   0
#four    1   2   0   1   0

# In this case I cheated and created it manually (order of columns is not important, order of rows is ideally preserved):
mydf <- data.frame(
  mon = c(0, 0, 0, 1),
  tue = c(1, 1, 0, 2),
  wed = c(1, 0, 0, 0),
  fri = c(1, 1, 0, 1),
  sun = c(0, 3, 0, 0)
)
rownames(mydf) <- c("one", "two", "three", "four")

我知道这可能是一种非标准的转变 - 有没有办法做到这一点?

修改 可能有必要知道原始数据看起来像这样:raw <- c("one:tue,wed,fri", "two:fri,sun,sun,tue,sun", "three", "four:tue,mon,tue,fri")

谢谢!

3 个答案:

答案 0 :(得分:3)

我们可以使用rbindlist

library(data.table)
rbindlist(lapply(mylist, as.data.frame.list), fill=TRUE)

或使用melt/acast

中的reshape2
library(reshape2)
acast(melt(mylist), L1~Var1, value.var="value", fill=0)

答案 1 :(得分:2)

以下是使用dplyrtidyr的解决方案:

library(dplyr)
library(tidyr)
mylist2 <- mylist %>%
  lapply(., function(i) spread(as.data.frame(i), Var1, Freq)) %>%
  bind_rows() %>%
  mutate_all(funs(ifelse(is.na(.), 0, .)))

结果:

> mylist2
  fri mon tue sun wed thu
1   1   1   1   0   0   0
2   0   1   0   1   3   0
3   1   0   1   0   0   2

答案 2 :(得分:1)

在@alexis_laz评论的基础上,我最终使用了这个解决方案:

dat <- read.table(text = raw, sep = ":", fill = TRUE, na.strings = "", stringsAsFactors = FALSE)
dat <- as.data.frame.matrix(t(table(stack(setNames(strsplit(dat$V2, ",", TRUE), dat$V1)))))