Search code examples
rdataframelistr-colnames

data.frame from lists in list, weird column names


I'm trying to make a data.frame from a "list in list"

l <- list(c("sam1", "GSM6683", "GSM6684", "GSM6687", "GSM6688"), c("sam2", 
"GSM6681", "GSM6682", "GSM6685", "GSM6686"))
df <- data.frame(l)

1) I get a date.frame with weird column names, how can I avoid it? 2) I'd like to get the column names from the first element of the inner list in list

like so:

column names: sam1, sam2
row1 GSM6683 GSM6681
row2 GSM6684 GSM6682
row3 GSM6687 GSM6685
row4 GSM6688 GSM6686

Solution

  • If you're starting with the data structure in your example, do this:

    df <- data.frame(lapply(l, function(x) x[-1]))
    names(df) <- lapply(l, function(x) x[1])
    

    If you have a choice on how to construct the data structure, do what R_Newbie says in his answer.