【问题标题】:understanding output of "order" function in R理解 R 中“order”函数的输出
【发布时间】:2020-05-11 23:21:12
【问题描述】:

给定这个数据框:

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 作为 tie-breaker 即虽然 Anna 和 Christian 都得分 10,但 Anna 的排名 == 1 & Christian 的 == 2

我的代码:test$rank_by_score &lt;- 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

我当前的输出发生了什么,如何获得我想要的输出?

编辑以在 agescores 编码为整数而不是因子时显示输出

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

【问题讨论】:

  • 请注意 cbind(names,scores, age) 将所有内容强制转换为字符,然后 data.frame(.) 默认为 stringsAsFactors = TRUE。现在分数被编码为最小的连续整数,10, not 5 ! 从向量中创建 df 的正确方法是不使用 @ 987654331@。去掉它,你的结果就完全不同了。
  • 在发布后注意到,但即使在调整后(使用cbind.data.frameas.int)排名也不合理
  • 是的,我知道排名仍然是错误的。我想说的是你不需要cbind,甚至不需要cbind.data.frame。方法是data.frame(names,scores, age)

标签: r ranking


【解决方案1】:

我认为您正在寻找 rank 而不是 orderrank 只能采用一列值。所以我们可以先order基于names的数据再使用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

order 按排序顺序返回原始向量的索引。

a1 <- order(test$scores, decreasing = TRUE)
a1
#[1] 1 3 4 5 2

a2 <- test$scores
a2
#[1] 10  5 10  9  8

这里order的输出可以解释为a2[a1[1]](10)是最大的数,其次是a2[a1[2]](10)和a2[a1[3]](9)等等。

数据

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)

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2015-12-03
    • 1970-01-01
    相关资源
    最近更新 更多