Sort string by specific values

I have the following line:

str1<-"{a{c}{b{{e}{d}}}}"

In addition, I have a list of integers:

str_d <- ( 1, 2, 2, 4, 4)

There is a one to one relationship between the list and the line. It means:

a 1
c 2
b 2
e 4
d 4

I would like to sort alphabetically only str1 characters having the same level. This means that for sorting c, b (which have the same value of 2) will give b, c and for sorting e, d (which have the same value of 4), they will give d, e.

The required result will be:

str2<-"{a{b}{c{{d}{e}}}}"

In addition, a, b, c, d and e can be not only characters, but can be words, such as:

str1<-"{NSP{ARD}{BOS{{DUD}{COR}}}}"

How can I do this by keeping {in their place?

+4
source share
2 answers
brkts <- gsub("\\w+", "%s", str1)
strings <- regmatches(str1,gregexpr("[^{}]+",str1))[[1]]
fixed <- ave(strings, str_d, FUN=function(x) sort(x))
do.call(sprintf, as.list(c(brkts, fixed)))
[1] "{a{b}{c{{d}{e}}}}"

and

[1] "{NSP{ARD}{BOS{{COR}{DUD}}}}"

. gsub %s. sprintf. strsplit , . fixed. , sprintf brkts, .

str_d <- c(1, 2, 2, 4, 4)
str1<-"{a{c}{b{{e}{d}}}}"
str1<-"{NSP{ARD}{BOS{{DUD}{COR}}}}"
+3

( stringr):

words <- str_extract_all(str1, '\\w+')[[1]]
ordered <- words[order(paste(str_d, words))]
formatter <- str_replace_all(str1, '\\w+', '%s')
do.call(sprintf, as.list(c(formatter, ordered)))

words . , str_d. . :

1 a 
2 c
2 b 
4 e 
4 d

sprintf().

+1

All Articles