[英]Rank variable by group (dplyr)
我有一個包含列x1, x2, group
的數據框,我希望生成一個新的數據幀,其中有一個額外的列rank
,表示其組中x1
的順序。
還有一個相關的問題在這里 ,但接受的答案似乎不工作了。
直到這里,沒關系:
library(dplyr)
data(iris)
by_species <- iris %>%
arrange(Species, Sepal.Length) %>%
group_by(Species)
但是當我試圖按組排名時:
by_species <- mutate(by_species, rank=row_number())
錯誤是:
排名錯誤(x,ties.method =“first”,na.last =“keep”):
參數“x”缺失,沒有默認值
更新
問題是dplyr
和plyr
之間dplyr
一些沖突。 要重現錯誤,請加載兩個包:
library(dplyr)
library(plyr)
data(iris)
by_species <- iris %>%
arrange(Species, Sepal.Length) %>%
group_by(Species) %>%
mutate(rank=row_number())
# Error in rank(x, ties.method = "first", na.last = "keep") :
# argument "x" is missing, with no default
卸載plyr
它應該工作:
detach("package:plyr", unload=TRUE)
by_species <- iris %>%
arrange(Species, Sepal.Length) %>%
group_by(Species) %>%
mutate(rank=row_number())
by_species %>% filter(rank <= 3)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species rank
## (dbl) (dbl) (dbl) (dbl) (fctr) (int)
## 1 4.3 3.0 1.1 0.1 setosa 1
## 2 4.4 2.9 1.4 0.2 setosa 2
## 3 4.4 3.0 1.3 0.2 setosa 3
## 4 4.9 2.4 3.3 1.0 versicolor 1
## 5 5.0 2.0 3.5 1.0 versicolor 2
## 6 5.0 2.3 3.3 1.0 versicolor 3
## 7 4.9 2.5 4.5 1.7 virginica 1
## 8 5.6 2.8 4.9 2.0 virginica 2
## 9 5.7 2.5 5.0 2.0 virginica 3
以下內容生成指定的所需結果。
library(dplyr)
by_species <- iris %>% arrange(Species, Sepal.Length) %>%
group_by(Species) %>%
mutate(rank = rank(Sepal.Length, ties.method = "first"))
by_species %>% filter(rank <= 3)
##Source: local data frame [9 x 6]
##Groups: Species [3]
##
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species rank
## (dbl) (dbl) (dbl) (dbl) (fctr) (int)
##1 4.3 3.0 1.1 0.1 setosa 1
##2 4.4 2.9 1.4 0.2 setosa 2
##3 4.4 3.0 1.3 0.2 setosa 3
##4 4.9 2.4 3.3 1.0 versicolor 1
##5 5.0 2.0 3.5 1.0 versicolor 2
##6 5.0 2.3 3.3 1.0 versicolor 3
##7 4.9 2.5 4.5 1.7 virginica 1
##8 5.6 2.8 4.9 2.0 virginica 2
##9 5.7 2.5 5.0 2.0 virginica 3
by_species %>% slice(1:3)
##Source: local data frame [9 x 6]
##Groups: Species [3]
##
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species rank
## (dbl) (dbl) (dbl) (dbl) (fctr) (int)
##1 4.3 3.0 1.1 0.1 setosa 1
##2 4.4 2.9 1.4 0.2 setosa 2
##3 4.4 3.0 1.3 0.2 setosa 3
##4 4.9 2.4 3.3 1.0 versicolor 1
##5 5.0 2.0 3.5 1.0 versicolor 2
##6 5.0 2.3 3.3 1.0 versicolor 3
##7 4.9 2.5 4.5 1.7 virginica 1
##8 5.6 2.8 4.9 2.0 virginica 2
##9 5.7 2.5 5.0 2.0 virginica 3
對於未來的讀者,可以使用基數R來實現按組變量排序。按照OP的iris
數據示例,根據Sepal.Length
進行排名:
# ORDER BY SPECIES AND SEPAL.LENGTH
iris <- iris[with(iris, order(Species, Sepal.Length)), ]
# RUN A ROW COUNT FOR RANK BY SPECIES GROUP
iris$rank <- sapply(1:nrow(iris),
function(i) sum(iris[1:i, c('Species')]==iris$Species[i]))
# FILTER DATA FRAME BY TOP 3
iris <- iris[iris$rank <= 3,]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.