neversaint
neversaint

Reputation: 63984

Renaming matrix rows in R

I have the following 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

and given this:

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

How can I get this?

        [,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

Upvotes: 1

Views: 7354

Answers (2)

Ken
Ken

Reputation: 1

Try this:

rownames(dat) <- c("f0","f1","f2","f3","f4","f5")

Upvotes: 0

Mikko
Mikko

Reputation: 7755

Maybe something like this?

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

If you already have a vector of names, then

rownames(dat) <- new_names

Upvotes: 4

Related Questions