gpt4 book ai didi

使用 apply 函数对排序后的数据集进行排名

转载 作者:行者123 更新时间:2023-12-02 21:24:04 27 4
gpt4 key购买 nike

我的数据框如下所示:

head(temp$HName)

[1] "UNIVERSITY OF TEXAS HEALTH SCIENCE CENTER AT TYLER"
[2] "METHODIST HOSPITAL,THE"
[3] "TOMBALL REGIONAL MEDICAL CENTER"
[4] "METHODIST SUGAR LAND HOSPITAL"
[5] "GULF COAST MEDICAL CENTER"
[6] "VHS HARLINGEN HOSPITAL COMPANY LLC"

head(temp$Rate)

[1] 7.3 8.3 8.7 8.7 8.8 8.9
76 Levels: 7.3 8.3 8.7 8.8 8.9 9 9.1 9.2 9.3 9.4 9.5 9.6 ... 17.1

> head(temp$Rank)
[1] NA NA NA NA NA NA

temp$Rate 已排序。我正在尝试编写一个函数 assignRank ,它为我提供了一个新列 temp$Rank ,其值为 1, 2, 3, 3, 4, 5

我的代码如下:

tapply(temp$Rank,temp$Rate, assignRank)

哪里:

    assignRank<- function(r=1){
temp$Rank <- r
r <- r + 1
return(r)
}

运行tapply时出现以下错误

   tapply(temp$Rank,temp$Rate, assignRank)
Show Traceback

Rerun with Debug
Error in `$<-.data.frame`(`*tmp*`, "Rank", value = c(NA, NA)) :
replacement has 2 rows, data has 301

请告诉我哪里出错了?

最佳答案

我使用 data.table 来做这样的事情,因为排序和排名都是非常高效/简单的语法

library(data.table)
setkey(setDT(temp), Rate) # This will sort your data set by Rate in case it's not yet sorted
temp[, Rank := .GRP, by = Rate]
temp
# HName Rate Rank
# 1: UNIVERSITY OF TEXAS HEALTH SCIENCE CENTER AT TYLER 7.3 1
# 2: METHODIST HOSPITAL,THE 8.3 2
# 3: TOMBALL REGIONAL MEDICAL CENTER 8.7 3
# 4: METHODIST SUGAR LAND HOSPITAL 8.7 3
# 5: GULF COAST MEDICAL CENTER 8.8 4
# 6: VHS HARLINGEN HOSPITAL COMPANY LLC 8.9 5

或者您可以使用基本 R 轻松执行相同操作(假设您的数据按排名排序),只需执行

as.numeric(factor(temp$Rate))
## [1] 1 2 3 3 4 5

或者也可以使用 dplyr 包中的 dense_rank 函数(这不需要需要对数据集进行排序)

library(dplyr)
temp %>%
mutate(Rank = dense_rank(Rate))
# HName Rate Rank
# 1 UNIVERSITY OF TEXAS HEALTH SCIENCE CENTER AT TYLER 7.3 1
# 2 METHODIST HOSPITAL,THE 8.3 2
# 3 TOMBALL REGIONAL MEDICAL CENTER 8.7 3
# 4 METHODIST SUGAR LAND HOSPITAL 8.7 3
# 5 GULF COAST MEDICAL CENTER 8.8 4
# 6 VHS HARLINGEN HOSPITAL COMPANY LLC 8.9 5

关于使用 apply 函数对排序后的数据集进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25803779/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com