My goal is to order multiple variables in a list in R:
" 5x^{5}" "-2x^{3}" "5x^{7}" "0" "1"
I want to get this order:
"5x^{7}" " 5x^{5}" "-2x^{3}" "1" "0"
So exponents from highest to lowest, then numerical order for the numbers. How can I achieve this? Decreasing for numerical alone is clear. For the exponents it would be necessary to detect if there is a x in the string and then extract the exponent and order it based on this. But I dont know how to do it.
CodePudding user response:
Well... it works
> x=c(" 5x^{5}","-2x^{3}","5x^{7}","0","1")
> x[order(gsub("(.*\\^\\{)(. )(\\}.*)","\\2",x),decreasing=T)]
[1] "5x^{7}" " 5x^{5}" "-2x^{3}" "1" "0"
CodePudding user response:
A more verbose option is to extract the exponents and the multipliers and then use arrange
. This has the advantage of having these numbers ready if you need to use them.
library(stringr)
library(dplyr)
dat <- data.frame(x = c(" 5x^{5}", "-2x^{3}", "5x^{7}", "0", "1"))
dat |> mutate(m = as.numeric(str_match(x, "([ -]*\\d )x\\^\\{(\\d)\\}")[, 2]),
exp = as.numeric(str_match(x, "([ -]*\\d )x\\^\\{(\\d)\\}")[, 3]),
n = as.numeric(x)) |>
arrange(desc(exp), desc(n))
Output
#> x m exp n
#> 1 5x^{7} 5 7 NA
#> 2 5x^{5} 5 5 NA
#> 3 -2x^{3} -2 3 NA
#> 4 1 NA NA 1
#> 5 0 NA NA 0
Created on 2022-06-13 by the reprex package (v2.0.1)
CodePudding user response:
Base R solution:
x[
order(
gsub(
".*\\{(\\d )\\}.*",
"\\1",
x
),
decreasing = TRUE
)
]
Input data:
x <- c(
" 5x^{5}",
"-2x^{3}",
"5x^{7}",
"0",
"1"
)