Ahdee
Ahdee

Reputation: 4949

Reverse/flip the sides of two strings based on a delimiter?

say I have the following strings.

st = c( "50/90", "cat/dog,sheep", "08/25,000")

is there a function I can use to flip the order based on the "/" delimiter?

c("90/50", "dog,sheep/cat", "25,000/08" ) 

Upvotes: 2

Views: 54

Answers (3)

Onyambu
Onyambu

Reputation: 79318

with(read.table(text=st, sep='/'), paste(V2, V1, sep='/'))

[1] "90/50"         "dog,sheep/cat" "25,000/08"

or even

do.call(paste, c(sep='/', rev(read.table(text=st, sep='/'))))

[1] "90/50"         "dog,sheep/cat" "25,000/08"    

Upvotes: 3

Gregor Thomas
Gregor Thomas

Reputation: 146050

We can write one pretty easily:

st = c( "50/90", "cat/dog,sheep", "08/25,000")
strsplit(st, "/", fixed = TRUE) |>
  lapply(rev) |>
  sapply(paste, collapse = "/")
# [1] "90/50"         "dog,sheep/cat" "25,000/08" 

Upvotes: 3

akrun
akrun

Reputation: 887691

We could capture as a group ((...)) and reverse the backreference (\\1, \\2) order

sub("^([^/]+)/(.*)", "\\2/\\1", st)
[1] "90/50"         "dog,sheep/cat" "25,000/08"   

Upvotes: 2

Related Questions