将单个列表名称放在列表的最后一列?

时间:2014-03-06 17:49:03

标签: r

我想分别将个别列表名称添加到最后一列。什么是有效地做到这一点的最好方法。

lst <- list(a=matrix(runif(10), nrow=5, ncol=2), b=matrix(runif(6), nrow=3, ncol=2))

$a
      [,1]       [,2]
[1,] 0.5257330 0.52673079
[2,] 0.2103107 0.23357179
[3,] 0.3745236 0.03687697
[4,] 0.9731074 0.15569480
[5,] 0.2248541 0.60258915

$b
      [,1]      [,2]
[1,] 0.9901820 0.3648310
[2,] 0.8922225 0.4285105
[3,] 0.6963518 0.5795353

我想要这个:这意味着应该在最后一列中添加单个列表名称。

$a
     [,1]                [,2]                 [,3]
[1,] "0.52573303761892"  "0.526730791199952"  "a" 
[2,] "0.210310699883848" "0.233571790158749"  "a" 
[3,] "0.374523550504819" "0.0368769748602062" "a" 
[4,] "0.973107369150966" "0.155694802291691"  "a" 
[5,] "0.224854125175625" "0.602589153219014"  "a" 

 $b
      [,1]                [,2]                [,3]
[1,] "0.990182007197291" "0.36483103595674"  "b" 
[2,] "0.892222490161657" "0.42851050500758"  "b" 
[3,] "0.696351842954755" "0.579535307129845" "b" 

任何帮助将不胜感激。

凯文

2 个答案:

答案 0 :(得分:2)

保留原始列表名称的解决方案:

mapply(function(x, y) cbind(x, y), lst, names(lst))

答案 1 :(得分:1)

这是一个可以满足您要求的解决方案。根据您的预期输出,您似乎意识到,通过这样做,您可以将矩阵中的数字强制转换为字符。

lapply(names(lst), function(x) {
  `colnames<-`(cbind(lst[[x]], x), NULL)
} )
# [[1]]
#      [,1]                [,2]                [,3]
# [1,] "0.497699242085218" "0.934705231105909" "a" 
# [2,] "0.717618508264422" "0.212142521282658" "a" 
# [3,] "0.991906094830483" "0.651673766085878" "a" 
# [4,] "0.380035179434344" "0.125555095961317" "a" 
# [5,] "0.777445221319795" "0.267220668727532" "a" 
# 
# [[2]]
#     [,1]                 [,2]                [,3]
# [1,] "0.386114092543721"  "0.86969084572047"  "b" 
# [2,] "0.0133903331588954" "0.34034899668768"  "b" 
# [3,] "0.382387957070023"  "0.482080115471035" "b"