R - list data.frame using list names

So, I have this list:

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

I want to get data.frame so that the two columns are scaf and pos

This, as I understand it:

 do.call(rbind, poor.loci) 

Desired Result:

 scaf pos HE638 8 HE638 8 HE638 8 
+6
source share
1 answer

Here are three options:

Option 1

Direct selection of any other element and the creation of your data.frame manually.

 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 

Option 2

Convert list to "long" data.frame and reshape it to the desired form. It can also be done with the "reshape2" package using melt and dcast instead of stack and reshape .

 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 

Option 3

data.frame list and convert the rebuilt list to 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)) 
+6
source

Source: https://habr.com/ru/post/959060/