[英]R sorting string vector based on a specific character without removing the last item in the vector
我有一個包含這些項目的向量
[1] "3 * x1" "-0.2 * x3" "-0.1 * x2" "-7.85"
是否可以根據 x 旁邊的值對其進行排序而不刪除最后一項,使其看起來像這樣
[1] "3 * x1" "-0.1 * x2" "-0.2 * x3""-7.85"
這樣的事情怎么樣:
vec <- c("3 * x1", "-0.2 * x3", "-0.1 * x2", "-7.85")
xsort <- function(vec){
l <- grepl("x\\d*", vec)
s <- as.numeric(gsub(".*x(\\d*).*", "\\1", vec))
s <- ifelse(l, s, Inf)
vec[order(s)]
}
xsort(vec)
#> [1] "3 * x1" "-0.1 * x2" "-0.2 * x3" "-7.85"
由reprex package (v2.0.1) 創建於 2022-10-03
vec2 <- gsub(".*\\bx([-+]?[0-9][.0-9]*)\\b.*", "\\1", vec)
vec2[vec2 == vec] <- ""
vec[order(suppressWarnings(as.numeric(vec2)))]
# [1] "3 * x1" "-0.1 * x2" "-0.2 * x3" "-7.85"
正則表達式:
".*\\bx([-+]?[0-9]\\.?[0-9]*)\\b.*"
.* .* anything, discard leading/following text
\\b \\b word-boundary
( ) capture group, "remember" within this --> \\1 later
[-+]? '-' or '+', optional
[0-9] at least one digit ...
\\.?[0-9]* ... followed by an optional dot and
zero or more digits
因為這在"-7.85"
的情況下沒有變化,所以我們需要通過檢查 "no change" 來跟進,如vec2 == vec
。
v <- c("3 * x1", "-0.2 * x3", "-0.1 * x2", "-7.85")
v[c(order(as.integer(sub(".*x", "", v[-length(v)]))), length(v))]
#> [1] "3 * x1" "-0.1 * x2" "-0.2 * x3" "-7.85"
另一種方法:
as.vector(names(sort(sapply(v, function(x) gsub('.*x','',x)))))
[1] "-7.85" "3 * x1" "-0.1 * x2" "-0.2 * x3"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.