【问题标题】:R - List to data.frame using list namesR - 使用列表名称列出到 data.frame
【发布时间】:2013-11-29 18:17:52
【问题描述】:

所以我有这个清单:

structure(list(scaf = structure(1L, .Label = "HE638", class = "factor"), 
    pos = 8L, scaf = structure(1L, .Label = "HE638", class = "factor"), 
    pos = 8L, scaf = structure(1L, .Label = "HE638", class = "factor"), 
    pos = 8L), .Names = c("scaf", "pos", "scaf", "pos", "scaf", 
"pos"))

我想得到一个data.frame,这样两列是scafpos

据我所知:

do.call(rbind, poor.loci)

想要的结果:

scaf     pos
HE638    8
HE638    8
HE638    8

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    这里有三个可供考虑的选项:

    选项 1

    直接选择所有其他元素并手动创建您的data.frame

    setNames(
      data.frame(unlist(poor.loci[c(TRUE, FALSE)], use.names = FALSE),
                 unlist(poor.loci[c(FALSE, TRUE)], use.names = FALSE)),
      unique(names(poor.loci)))
    #    scaf pos
    # 1 HE638   8
    # 2 HE638   8
    # 3 HE638   8
    

    选项 2

    将您的list 转换为“长”data.frame 并将reshape 转换为您想要的形式。也可以使用“reshape2”包使用meltdcast 而不是stackreshape

    X <- stack(lapply(poor.loci, as.character))
    X$ID <- ave(X$values, X$values, FUN = seq_along)
    reshape(X, direction = "wide", idvar="ID", timevar="ind")
    #   ID values.scaf values.pos
    # 1  1       HE638          8
    # 3  2       HE638          8
    # 5  3       HE638          8
    

    选项 3

    重新排列您的list 并将重新排列的list 转换为data.frame

    A <- unique(names(poor.loci))
    data.frame(
      setNames(
        lapply(A, function(x) unlist(poor.loci[names(poor.loci) %in% x], 
                                     use.names = FALSE)), A))
    

    【讨论】:

    • 还有一个:as.data.frame(lapply(split(ll, names(ll)), unlist))
    • @flodel 另一个没有lapply的是:as.data.frame(split(unlist(poor.loci), names(poor.loci)))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多