Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Convert Row Labels To Column

Using R I have been passed (from another programmer whose code I cannot touch) a matrix of numbers that have column and row names labelled. Something like this:

       Height    Width
Chair     25       26
Desk      18       48

I want to convert this into a data from the matrix above into a data frame that is in the following format:

            Height   Width
[1,] Chair     25      26 
[2,] Desk      18      48

Where the first column name is a (' '). I do not know the Row names in advance and I cannot change the original code. How would I convert this simply and efficiently using R?

In other words I simply want to place row names into the data set.

like image 299
Brent Avatar asked Jan 21 '26 05:01

Brent


2 Answers

M <- matrix(c(25,18,26,48), 2)
rownames(M) <- c("Chair", "Desk")
colnames(M) <- c("Height", "Width")

DF <- data.frame(furniture=rownames(M), M)
rownames(DF) <- NULL
#   furniture Height Width
# 1     Chair     25    26
# 2      Desk     18    48 
like image 200
Roland Avatar answered Jan 23 '26 21:01

Roland


Hi i think this do what you want :

mat <- matrix(c(25, 18, 26, 48), nrow = 2, dimnames = list(c("Chair", "Desk"), c("Height", "Width")))

 df <- data.frame(row.names(mat), mat, row.names = NULL)

> df
 row.names.mat. Height Width
1          Chair     25    26
2           Desk     18    48
like image 36
Julien Navarre Avatar answered Jan 23 '26 19:01

Julien Navarre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!