如何使用dplyr
根据多列的递减值为每一列创建等级?
以下代码似乎没有考虑desc
arrange_at
参数
rank_f <- function(ds, cols, fs){
ds %>%arrange_at(desc(vars(!!!cols)))%>%
mutate_at(vars(!!!cols), funs(!!!fs))
}
USArrests %>%tibble::rownames_to_column()%>%
rank_f(quos((Murder:Rape)),quos(min_rank))->ranked
head(USArrests)
# Murder Assault UrbanPop Rape
# Alabama 13.2 236 58 21.2
# Alaska 10.0 263 48 44.5
# Arizona 8.1 294 80 31.0
# Arkansas 8.8 190 50 19.5
# California 9.0 276 91 40.6
# Colorado 7.9 204 78 38.7
head(ranked)
# rowname Murder Assault UrbanPop Rape
# 1 Alabama 44 35 16 29
# 2 Alaska 35 43 7 49
# 3 Arizona 29 47 39 43
# 4 Arkansas 31 31 9 24
# 5 California 32 44 50 48
# 6 Colorado 28 33 38 47
费率越高,排名就应该越低。
答案 0 :(得分:0)
我们需要将其放置在funs
out1 <- USArrests %>%
tibble::rownames_to_column() %>%
arrange_at(vars(Murder:Rape), funs(desc))
在每列上应用desc
进行检查
out2 <- USArrests %>%
tibble::rownames_to_column() %>%
arrange(desc(Murder), desc(Assault), desc(UrbanPop), desc(Rape))
identical(out1, out2)
#[1] TRUE
基于上述内容,我们可以在rank_f
out3 <- out2 %>%
mutate_at(vars(Murder:Rape), min_rank)
rank_f <- function(ds, cols, fs){
ds %>%
arrange_at(vars(!!!cols), funs(desc))%>%
mutate_at(vars(!!!cols), funs(!!!fs))
}
out4 <- USArrests %>%
tibble::rownames_to_column()%>%
rank_f(quos((Murder:Rape)),quos(min_rank))
identical(out3, out4)
#[1] TRUE
根据OP的评论,我们不需要做任何arrange
,我们可以通过将列值转换为负数来直接应用min_rank
USArrests %>%
tibble::rownames_to_column() %>%
mutate_at(vars(Murder:Rape), funs(min_rank(-.)))