Brent
Brent

Reputation: 313

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.

Upvotes: 3

Views: 4476

Answers (2)

Julien Navarre
Julien Navarre

Reputation: 7840

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

Upvotes: 1

Roland
Roland

Reputation: 132989

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 

Upvotes: 2

Related Questions