Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a table that have the following values:

School---- Location----Score

Bexley -----  OH ------ 4.9

Obetz ------ OH ------- 3.4

Harper ------ OH ------- 3.1

Willow ----- NY --------4.3

Sancus ----- NY --------4.0

Roberts ----- NY --------4.1

I'm trying to either derive the rank data or actually add a column that would show the rank of each row per School. So something like this:

School ----- Location ----- Score --- Rank

Bexley -----  OH ------ 4.9 ------ 1

Obetz ------ OH ------- 3.4 ------ 2

Harper ------ OH ------- 3.1 ------3

Willow ----- NY --------4.3 ------- 1

Sancus ----- NY --------4.0 ------3

Roberts ----- NY --------4.1 ------2

I don't necessarily need to add the rank as a row to the table, as long as I can drive the rankings and list them upon another command, etc.

Any thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
164 views
Welcome To Ask or Share your Answers For Others

1 Answer

The rank function ranks from low to high, and using a minus sign reverses the scores. Use the ave function to apply rank by groups.

data <- read.table(text="School     Location    Score
Bexley       OH        4.9
Obetz        OH         3.4
Harper        OH         3.1
Willow       NY         4.3
Sancus       NY         4.0
Roberts       NY         4.1", 
stringsAsFactors =F,header=T)
data$Rank <- ave( -data$Score, data$Location, FUN=rank )
data
   School Location Score Rank
1  Bexley       OH   4.9    1
2   Obetz       OH   3.4    2
3  Harper       OH   3.1    3
4  Willow       NY   4.3    1
5  Sancus       NY   4.0    3
6 Roberts       NY   4.1    2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...