展平一个命名的向量列表

时间:2017-05-26 16:45:53

标签: r

我的列表看起来像这样:

things <- list(
    "thing1" = "foo",
    "thing2" = "bar",
    "thing4" = c("baz", "qux"),
    "thing5" = c("quux", "quuz", "corge"),
    "thing6" = "grault"
)

我想要一个解决方案,将不规则列表转换为如下字符矩阵:

+----------+----------+
| "thing1" | "foo"    |
| "thing2" | "bar"    |
| "thing4" | "baz"    |
| "thing4" | "qux"    |
| "thing5" | "quux"   |
| "thing5" | "quuz"   |
| "thing5" | "corge"  |
| "thing6" | "grault" |
+----------+----------+

真实的例子太长了,无法手工完成。

3 个答案:

答案 0 :(得分:6)

您可以尝试:

as.matrix(stack(things))[, c(2, 1)]

#     ind      values  
# [1,] "thing1" "foo"   
# [2,] "thing2" "bar"   
# [3,] "thing4" "baz"   
# [4,] "thing4" "qux"   
# [5,] "thing5" "quux"  
# [6,] "thing5" "quuz"  
# [7,] "thing5" "corge" 
# [8,] "thing6" "grault"

答案 1 :(得分:3)

另一种可能性(在基础R中):

cbind(rep(names(things), times = lengths(things)), unname(unlist(things)))

#     [,1]     [,2]    
#[1,] "thing1" "foo"   
#[2,] "thing2" "bar"   
#[3,] "thing4" "baz"   
#[4,] "thing4" "qux"   
#[5,] "thing5" "quux"  
#[6,] "thing5" "quuz"  
#[7,] "thing5" "corge" 
#[8,] "thing6" "grault"

答案 2 :(得分:3)

我们可以使用function putZeroToLastItem($text) { $length = strlen($text); if( $length < 9 ) { $text .= '0' } return $text }

melt