Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R rename duplicate col and rownames (subindexing)

Tags:

r

matrix

I would very much appreciate if a kind soul could tell me how to do this in R:

Given a squared matrix with duplicated columns and rows, such as

       1     1     2     2     2     2     3
1  0.000 0.000 0.048 0.048 0.048 0.048 0.059
1  0.000 0.000 0.048 0.048 0.048 0.048 0.059
2  0.048 0.048 0.000 0.000 0.000 0.000 0.059
2  0.048 0.048 0.000 0.000 0.000 0.000 0.059
2  0.048 0.048 0.000 0.000 0.000 0.000 0.059
2  0.048 0.048 0.000 0.000 0.000 0.000 0.059
3  0.059 0.059 0.059 0.059 0.059 0.059 0.000

where same col and row names designate duplicates, I require to have unique col and row names, while keeping track of original and duplicate cols/rows. That is, something like

        1    1a     2    2a    2b    2c     3
1   0.000 0.000 0.048 0.048 0.048 0.048 0.059
1a  0.000 0.000 0.048 0.048 0.048 0.048 0.059
2   0.048 0.048 0.000 0.000 0.000 0.000 0.059
2a  0.048 0.048 0.000 0.000 0.000 0.000 0.059
2b  0.048 0.048 0.000 0.000 0.000 0.000 0.059
2c  0.048 0.048 0.000 0.000 0.000 0.000 0.059
3   0.059 0.059 0.059 0.059 0.059 0.059 0.000

Thanks in advance

like image 301
JABalbuena Avatar asked Sep 12 '13 14:09

JABalbuena


People also ask

How do I rename a column by index in R?

How to rename column by index in the R data frame? R provides base function colnames() and names() function to change column name by index position. Besides these, use dplyr rename() , select() and rename_with() to rename/change a DataFrame (data. frame) column.

How do I rename rows and columns in R?

Rename Column using colnames() colnames() is the method available in R base which is used to rename columns/variables present in the data frame. By using this you can rename a column by index and name. Alternatively, you can also use name() method.

How do I rename multiple column headers in R?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.


1 Answers

You could use ?make.unique or ?make.names:

v <- as.character(c(1, 1, 2, 2, 2, 2, 3))
make.unique(v)
# [1] "1"   "1.1" "2"   "2.1" "2.2" "2.3" "3"

(You have to combine this with rownames and colnames.)

like image 171
sgibb Avatar answered Nov 15 '22 19:11

sgibb