-1

Suppose I have a matrix, mx, with named rows and columns, with hundreds of rows/columns. A sample looks like:

   ABC DEF GHI
ABC 1   0   1
DEF 0   1   0
GHI 0   0   1

And suppose I have a data frame called df with two columns which looks like:

letters country
ABC     UK
DEF     USA
GHI     Egypt

I want to rename the rows and columns in mx based on the corresponding country values in df.

I.e. I would like mx to become:

      UK USA Egypt
UK    1   0   1
USA   0   1   0
Egypt 0   0   1

Does anyone know whether this is possible in R?

HelpMe
  • 87
  • 1
  • 8

1 Answers1

2

You may try

x <- colnames(mx) # = rownames(mx)
df$country[match(x, df$letters)]
colnames(mx) <- df$country[match(x, df$letters)]
#rownames(mx) <- df$country[match(x, df$letters)]
Park
  • 14,771
  • 6
  • 10
  • 29
  • 1
    The logic is the same, but you could even do both `dimnames` in one go - `dimnames(mx) <- lapply(dimnames(mx), \(x) df$country[match(x, df$letters)] )` – thelatemail Jun 08 '22 at 00:46
  • Thanks! This works but now the row names save like `USA.1`, `USA.2` etc. where I have repeats. Is there a way to remove '.' and numbers from the row names? – HelpMe Jun 08 '22 at 00:56
  • @HelpMe Take a look at https://stackoverflow.com/questions/10617702/remove-part-of-string-after – Park Jun 08 '22 at 01:05