Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing dimnames of matrices and data frames in R

Let's say I have created the following matrix:

> x <- matrix(1:20000,nrow=100)
> x[1:10,1:10]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1  101  201  301  401  501  601  701  801   901
 [2,]    2  102  202  302  402  502  602  702  802   902
 [3,]    3  103  203  303  403  503  603  703  803   903
 [4,]    4  104  204  304  404  504  604  704  804   904
 [5,]    5  105  205  305  405  505  605  705  805   905
 [6,]    6  106  206  306  406  506  606  706  806   906
 [7,]    7  107  207  307  407  507  607  707  807   907
 [8,]    8  108  208  308  408  508  608  708  808   908
 [9,]    9  109  209  309  409  509  609  709  809   909
[10,]   10  110  210  310  410  510  610  710  810   910

What are the methods in R to change row and column names? For example, I like row names to be SS1, SS2, ..., SS100 and column names to be M1, M2, ..., M200. I usually work with data with 1000s of rows and columns, and I need a good method to do that. Some people use something like attributes(x)$dimnames <- list(...) and some use rownames <- paste(...). What are all possible methods?

My second question is, can I use the same methods after I convert the matrix to a data frame?

like image 905
Mehper C. Palavuzlar Avatar asked Feb 19 '10 13:02

Mehper C. Palavuzlar


People also ask

What is the key difference between a matrix and a data frame in R?

In a data frame the columns contain different types of data, but in a matrix all the elements are the same type of data. A matrix in R is like a mathematical matrix, containing all the same type of thing (usually numbers). R often but not always lets these be used interchangably.

How do I convert a data matrix to a Dataframe in R?

A matrix can be converted to a dataframe by using a function called as. data. frame(). It will take each column from the matrix and convert it to each column in the dataframe.

What is the key difference between a matrix and a data frame in R provide an example to demonstrate the difference?

Both represent 'rectangular' data types, meaning that they are used to store tabular data, with rows and columns. The main difference, as you'll see, is that matrices can only contain a single class of data, while data frames can consist of many different classes of data.

How do you name rows and columns in Dataframe and matrices F in R?

Naming Rows and Columns of a Matrix in R Programming – rownames() and colnames() Function. rownames() function in R Language is used to set the names to rows of a matrix.


1 Answers

From comment to answer:

row.names(x) <- paste("SS", 1:nrow(x), sep="")
colnames(x) <-  paste("M" , 1:ncol(x), sep="")

As @doug wrote, it works for matrices and data frames.

like image 50
Marek Avatar answered Oct 17 '22 05:10

Marek