How to convert a named list of named vectors into a data.frame conveniently?

advertisements

Suppose I have the following named list of named vectors:

structure(list(var1 = structure(c(-0.59588185761272, -1.40360179042903,
-0.930940964040855, 0.627327161612272, 2.5718263501814, -0.494398712878508
), .Names = c("W", "X", "J", "V", "Y", "A")), var2 = structure(0.845082248473655, .Names = "K"),
    var3 = structure(c(-0.0445511021832538, 1.29597344526442), .Names = c("B",
    "C"))), .Names = c("var1", "var2", "var3"))

# $var1
#          W          X          J          V          Y          A
# -0.5958819 -1.4036018 -0.9309410  0.6273272  2.5718264 -0.4943987
#
# $var2
#         K
# 0.8450822
#
# $var3
#          B          C
# -0.0445511  1.2959734

How do I derive a data.frame of values, names of vectors and names of lists. derived output looks like this:

#       values vec var.name
# 1 -0.5958819   W     var1
# 2 -1.4036018   X     var1
# 3 -0.9309410   J     var1
# 4  0.6273272   V     var1
# 5  2.5718264   Y     var1
# 6 -0.4943987   A     var1
# 7  0.8450822   K     var2
# 8 -0.0445511   B     var3
# 9  1.2959734   C     var3

I tried stack but it ignores the names of vectors.


# OPs data
d <- structure(list(var1 = structure(c(-0.59588185761272, -1.40360179042903,
-0.930940964040855, 0.627327161612272, 2.5718263501814, -0.494398712878508
), .Names = c("W", "X", "J", "V", "Y", "A")), var2 = structure(0.845082248473655, .Names = "K"),
    var3 = structure(c(-0.0445511021832538, 1.29597344526442), .Names = c("B",
    "C"))), .Names = c("var1", "var2", "var3"))

# Solution
d <- unlist(d)
data.frame(value = d,
           vec = gsub(".*\\.", "", names(d)),
           var.name =  gsub("\\..*", "", names(d)))