对于情况相似的系统,您可能有一个要排序的变量,但最初希望按照一个辅助变量的顺序排序,以便根据辅助变量首次出现的顺序对其进行排序。
在下面的函数中,初始排序变量称为order_by
,辅助变量称为order_along
——即“沿着初始顺序根据此变量排序”。
library(dplyr, warn.conflicts = FALSE)
df <- structure(
list(
msoa11hclnm = c(
"Bewbush", "Tilgate", "Felpham",
"Selsey", "Brunswick", "Ratton", "Ore", "Polegate", "Mile Oak",
"Upperton", "Arundel", "Kemptown"
),
lad20nm = c(
"Crawley", "Crawley",
"Arun", "Chichester", "Brighton and Hove", "Eastbourne", "Hastings",
"Wealden", "Brighton and Hove", "Eastbourne", "Arun", "Brighton and Hove"
),
shape_area = c(
1328821, 3089180, 3540014, 9738033, 448888, 10152663, 5517102,
7036428, 5656430, 2653589, 72832514, 826151
)
),
row.names = c(NA, -12L), class = "data.frame"
)
这不能满足我的需求:
df %>%
dplyr::arrange(shape_area, lad20nm)
这里是一个函数:
order_along <- function(df, order_along, order_by) {
cols <- colnames(df)
df <- df %>%
dplyr::arrange({{ order_by }})
df %>%
dplyr::select({{ order_along }}) %>%
dplyr::distinct() %>%
dplyr::full_join(df) %>%
dplyr::select(dplyr::all_of(cols))
}
order_along(df, lad20nm, shape_area)
2021年1月12日由reprex package (v0.3.0)创建
b,c,a,d,b,c,a,d
。我尝试了match
但是它效果不好。 - Yulongmatch()
之前,您必须明确确保重复项已被删除。我想到的是duplicated()
、unique()
或其他一些自定义程序,可以“保留”所需元素并丢弃其他元素。希望对您有所帮助。 - Rappster