简体   繁体   English

R 根据特定字符对字符串向量进行排序,而不删除向量中的最后一项

[英]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是否可以根据 x 旁边的值对其进行排序而不删除最后一项,使其看起来像这样

[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)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"    

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 .因为这在"-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"

Another approach:另一种方法:

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.

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