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.
An alternative to your two-step solution using do.call(rbind
+ stack
and then adding in "var.name" would be to use rbindlist
from "data.table":
library(data.table)
rbindlist(lapply(L, stack), idcol = TRUE)
## .id values ind
## 1: var1 -0.5958819 W
## 2: var1 -1.4036018 X
## 3: var1 -0.9309410 J
## 4: var1 0.6273272 V
## 5: var1 2.5718264 Y
## 6: var1 -0.4943987 A
## 7: var2 0.8450822 K
## 8: var3 -0.0445511 B
## 9: var3 1.2959734 C
# 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)))
There are two alternative solutions in comment that I would like to summarize it here:
from lmo:
df_new <- stack(df)
df_new$vec <- unlist(lapply(df, names))
My solution. stack
works on a named vector too (by calling as.list):
df2 <- do.call(rbind, lapply(df, stack))
df2$var.name <- rep(names(df), lengths(df))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.