如何方便地将命名向量的命名列表转换为data.frame?

时间:2017-04-14 12:41:58

标签: r list dataframe

假设我有以下命名的矢量列表:

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 

如何派生data.frame个值,向量名称和列表名称。派生输出如下所示:

#       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

我尝试过堆叠,但它忽略了向量的名称。

3 个答案:

答案 0 :(得分:4)

使用do.call(rbind + stack替代您的两步解决方案,然后添加" var.name"将使用来自" data.table":

rbindlist
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

答案 1 :(得分:1)

# 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)))

答案 2 :(得分:1)

评论中有两种备选解决方案,我想在此总结一下:

来自lmo的

dfNew <- stack(df)
df$vec <- unlist(lapply(df, names))

我的解决方案。 stack也适用于命名向量(通过调用as.list):

df2 <- do.call(rbind, lapply(df, stack))
df2$var.name <- rep(names(df), lengths(df))