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

标签 r dataframe tidyverse

我有一个名为 listtable就像这样:

# 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")

谢谢!

最佳答案

我们可以使用rbindlist

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

或者使用 reshape2 中的 melt/acast

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

关于r - 将表的命名列表转换为 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488302/

相关文章:

pandas - 设置 pandas 索引单元格的背景颜色

python - Seaborn 线图和条形图在 X 轴上不对齐

r - 如何使用可以与 c() 组合的 R vctrs 包构建对象

r - 如何在 dplyr::mutate() 的 RHS 上使用动态变量?

r - 我可以将一个 PCA 的变量坐标叠加到第二个 PCA 的个体坐标上并仍然解释结果吗?

r - 在 R 中选择 n 个最远的点

python - 使用 pandas.merge_asof 进行全外连接

r - 'RJDBC' 的 dbSendStatement() 中的 ORA-00900 错误

regex - 是否有一个R函数来查找字符向量中的regexp匹配索引?

R,按组递归地将文本从一行添加到另一行