6

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 a data.frame so that the two columns are scaf and pos

This is as far as I've gotten:

do.call(rbind, poor.loci)

Desired result:

scaf     pos
HE638    8
HE638    8
HE638    8

1 Answer 1

6

Here are three options to consider:

Option 1

Straightforward selecting of every other element and manually creating your 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

Option 2

Convert your list into a "long" data.frame and reshape it to the form you want. 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

Rearrange your list and convert the rearranged list to a 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))
Sign up to request clarification or add additional context in comments.

2 Comments

one more: as.data.frame(lapply(split(ll, names(ll)), unlist))
@flodel Another one without lapply is: as.data.frame(split(unlist(poor.loci), names(poor.loci))).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.