简体   繁体   中英

How to change row and column names based on values in another data frame in R?

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 .

Ie 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?

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM