R - 使用列表名称列出到data.frame

时间:2013-11-29 18:17:53

标签: r dataframe

所以我有这个清单:

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

1 个答案:

答案 0 :(得分:6)

以下三个选项需要考虑:

选项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转换为您想要的格式。也可以使用meltdcast代替stackreshape使用“reshape2”套餐。

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