如何根据排序的数字矩阵对字符矩阵进行排序?

问题描述 投票:1回答:1

我有一个学生的grades矩阵。

         Winston  Ariana  James
Math          50      70     90
Science       85      90     50
Biology       40      30     80

如何将该矩阵转换为学生表现最佳的课程排序矩阵?

Winston   Ariana   James
Science   Science  Math 
Math      Math     Biology
Biology   Biology  Science

我有想法使用gradesapply(grades, 2, sort, decreasing=TRUE)矩阵进行排序,然后创建一个矩阵(我们称之为temp),如下所示:matrix(rownames(grades), nrow=nrow(grades), ncol=ncol(grades), dimnames=list(c(NULL), c(colnames(grades)))),其中temp矩阵的每一行都将由等级的rownames填充。然后以某种方式将grades的值传递给temp,然后我对它进行排序。

任何人都可以帮助更好地解决这个问题,或者让我知道如何在不改变grades元素的情况下将temp的值传递给temp

r
1个回答
1
投票

我们将matrix转换为data.frame,创建rownames作为列(rownames_to_column),mutate列除了第一个,通过order值按递减顺序然后使用它来索引重新排列每列中的rownames,转换'rn'列回到rownames并再次将其更改为matrix

library(tidyverse)
m1 %>% 
  as.data.frame %>% 
  rownames_to_column('rn') %>%
  mutate_at(-1, list(~ rn[order(., decreasing = TRUE)])) %>%
  column_to_rownames('rn') %>%
  as.matrix
#     Winston   Ariana    James    
#Math    "Science" "Science" "Math"   
#Science "Math"    "Math"    "Biology"
#Biology "Biology" "Biology" "Science"

或者我们可以将melt变成'long'格式,以'long'形式执行arrange,然后执行spread

library(reshape2)
melt(m1) %>%
   arrange(Var2, desc(value)) %>% 
   group_by(Var2) %>%      
   mutate(rn = row_number()) %>%
   dplyr::select(-value) %>% 
   spread(Var2, Var1)

或者使用base R,循环遍历matrix列,order列值按降序排列,使用索引按顺序排列rownames

apply(m1, 2, function(x) row.names(m1)[order(x, decreasing = TRUE)])
#    Winston   Ariana    James    
#[1,] "Science" "Science" "Math"   
#[2,] "Math"    "Math"    "Biology"
#[3,] "Biology" "Biology" "Science"

data

m1 <- structure(c(50L, 85L, 40L, 70L, 90L, 30L, 90L, 50L, 80L), .Dim = c(3L, 
 3L), .Dimnames = list(c("Math", "Science", "Biology"),
  c("Winston", "Ariana", "James")))
© www.soinside.com 2019 - 2024. All rights reserved.