我有一个学生的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
我有想法使用grades
对apply(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
?
我们将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"
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")))