重命名R中的矩阵行

时间:2012-05-15 09:28:50

标签: r matrix

我有以下矩阵:

> dat

       [,1]      [,2]       [,3]        [,4]
foo 0.7574657 0.2104075 0.02922241 0.002705617
foo 0.0000000 0.0000000 0.00000000 0.000000000
foo 0.0000000 0.0000000 0.00000000 0.000000000
foo 0.0000000 0.0000000 0.00000000 0.000000000
foo 0.0000000 0.0000000 0.00000000 0.000000000
foo 0.0000000 0.0000000 0.00000000 0.000000000

并且给出了这个:

> new_names <- c("f0","f1","f2","f3","f4","f5");
# where the length of new_names matches the number of rows in the dat matrix

我怎么能得到这个?

        [,1]      [,2]       [,3]        [,4]
f0 0.7574657 0.2104075 0.02922241 0.002705617
f1 0.0000000 0.0000000 0.00000000 0.000000000
f2 0.0000000 0.0000000 0.00000000 0.000000000
f3 0.0000000 0.0000000 0.00000000 0.000000000
f4 0.0000000 0.0000000 0.00000000 0.000000000
f5 0.0000000 0.0000000 0.00000000 0.000000000

2 个答案:

答案 0 :(得分:4)

也许是这样的?

dat <- matrix(c(c(0.7574657, 0.2104075, 0.02922241, 0.002705617), rep(0, 4*6-4)), ncol = 4, nrow = 6, byrow = TRUE)

rownames(dat) <- paste0("f", seq(0, nrow(dat)-1))

如果您已有名字矢量,那么

rownames(dat) <- new_names

答案 1 :(得分:0)

试试这个:

  

rownames(dat)&lt; - c(&#34; f0&#34;,&#34; f1&#34;,&#34; f2&#34;,&#34; f3&#34;,&# 34; F4&#34;&#34; F5&#34)