了解R中“ order”函数的输出

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

给出此数据框:

names <- c("Anna", "Bella", "Christian", "Derrick", "Emma")
scores <- c(10,5,10,9,8)
age <- c(16,16,17,18,21)
test <- data.frame(cbind(names,scores, age))

我希望创建一个变量,该变量以scores排名,并使用names作为平局即尽管安娜和克里斯蒂安都得分10,但安娜的排名== 1和克里斯蒂安的== 2

我的代码:test$rank_by_score <- order(test$scores, test$names, decreasing = T)

当前输出:

names      scores   age   rank_by_score
Anna       10       16    4
Bella      5        16    5
Christian  10       17    2
Derrick    9        18    3
Emma       8        21    1

期望的输出:

names      scores   age   rank_by_score
Anna       10       16    1
Bella      5        16    5
Christian  10       17    2
Derrick    9        18    3
Emma       8        21    4

当前输出中发生了什么,如何获得所需的输出?

r ranking
1个回答
0
投票

我认为您正在寻找rank而不是order,但rank只能使用一个列值。因此,我们可以首先基于ordernames数据,然后使用rank

test <- test[order(test$names), ]

rank(-test$scores, ties.method = "first")
#[1] 1 5 2 3 4

请参见?rank了解不同的ties.method选项。如果我们在有平局的情况下使用ties.method = "first",则为ties.method = "last"出现在第一个与第一个相反的条目赋予较小的数字。

rank(-test$scores, ties.method = "last")
#[1] 2 5 1 3 4

数据

names <- c("Anna", "Bella", "Christian", "Derrick", "Emma")
scores <- c(10,5,10,9,8)
age <- c(16,16,17,18,21)
test <- data.frame(names, scores, age)
© www.soinside.com 2019 - 2024. All rights reserved.