所以我有这个清单:
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,以便这两列是scaf
和pos
就我而言:
do.call(rbind, poor.loci)
期望的结果:
scaf pos
HE638 8
HE638 8
HE638 8
答案 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
转换为您想要的格式。也可以使用melt
和dcast
代替stack
和reshape
使用“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))