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" )
CodePudding user response:
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"
CodePudding user response:
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"
CodePudding user response:
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"