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

Time:10-04

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"

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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"

CodePudding user response:

Another approach:

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