r - How to convert a named list of named vectors to a data.frame conveniently? -
suppose have 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 # -0.5958819 -1.4036018 -0.9309410 0.6273272 2.5718264 -0.4943987 # # $var2 # k # 0.8450822 # # $var3 # b c # -0.0445511 1.2959734
how derive data.frame
of values, names of vectors , names of lists. derived output looks 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 var1 # 7 0.8450822 k var2 # 8 -0.0445511 b var3 # 9 1.2959734 c var3
i tried stack ignores 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)))
Comments
Post a Comment