简体   繁体   中英

R sorting string vector based on a specific character without removing the last item in the vector

I have a vector containing these items

[1] "3 * x1" "-0.2 * x3" "-0.1 * x2" "-7.85"

Is it possible to sort it based on the value beside x without removing the last item in such a way that it will look like this

[1] "3 * x1" "-0.1 * x2" "-0.2 * x3""-7.85"

How about something like this:

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"

Created on 2022-10-03 by the reprex package (v2.0.1)

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"    

Regex:

".*\\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

Because this makes no change in the case of "-7.85" , we need to follow-up by checking for "no change", as in 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"

Another approach:

as.vector(names(sort(sapply(v, function(x) gsub('.*x','',x)))))
[1] "-7.85"     "3 * x1"    "-0.1 * x2" "-0.2 * x3"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM