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
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.
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.
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.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With