flatten a data frame

speendo picture speendo · Feb 27, 2012 · Viewed 15.7k times · Source

I have this nested data frame

test <- structure(list(id = c(13, 27), seq = structure(list(
`1` = c("1997", "1997", "1997", "2007"),
`2` = c("2007", "2007", "2007", "2007", "2007", "2007", "2007")), 
.Names = c("1", "2"))), .Names = c("penr", 
"seq"), row.names = c("1", "2"), class = "data.frame")

I want a list of all values in the second column, namely

result <- c("1997", "1997", "1997", "2007", "2007", "2007", "2007", "2007", "2007", "2007", "2007")

Is there an easy way to achieve this?

Answer

Paul Hiemstra picture Paul Hiemstra · Feb 27, 2012

This line does the trick:

do.call("c", test[["seq"]])

or equivalent:

c(test[["seq"]], recursive = TRUE)

or even:

unlist(test[["seq"]])

The output of these functions is:

    11     12     13     14     21     22     23     24     25     26     27 
"1997" "1997" "1997" "2007" "2007" "2007" "2007" "2007" "2007" "2007" "2007" 

To get rid of the names above the character vector, call as.character on the resulting object:

> as.character((unlist(test[["seq"]])))
 [1] "1997" "1997" "1997" "2007" "2007" "2007" "2007" "2007" "2007" "2007"
[11] "2007"