0

I'm trying to reverse the parts of a hierarchical name found in a dataframe so that I can work with the string for the reverse path. Here is what I did:

flip <- function(x) {                      # My attempted function
  str <- str_split(x,":",simplify=TRUE)
  paste(str[length(str):1], collapse = ":")
}

Data <- data.frame(                        # The data
  X = c("one:two:three:four","five:six:seven:eight")
)

mutate(Data,                               # My attempt & result
   Xflip = flip(X)
)
#>                     X                Xflip
#>1   one:two:three:four eight:four:seven:three:six:two:five:one
#>2 five:six:seven:eight eight:four:seven:three:six:two:five:one


# What I am looking for
#>                     X                Xflip
#>1   one:two:three:four   four:three:two:one
#>2 five:six:seven:eight eight:seven:six:five

Thank you!

A. Maffei
  • 3
  • 4
  • My apologies -- there are some typos in my example above. I will edit my example. Thanks for response so far. – A. Maffei Mar 06 '18 at 22:58
  • It's not clear to me that this is an exact duplicate as I need to reverse the parts of a delimited string rather than each character in the string. I've edited the title to reflect this difference. I note that in the "How to reverse a string in R" article a strsplit is performed but employs NULL as delimiter - not sure why. – A. Maffei Mar 12 '18 at 00:31

2 Answers2

1

Or using stringr::str_split_fixed:

df$Xflip <- apply(stringr::str_split_fixed(df$X, ":", 4), 1, function(x) 
    paste0(rev(x), collapse = ":"))
#                     X                Xflip
#1   one:two:three:four   four:three:two:one
#2 five:six:seven:eight eight:seven:six:five

Or using stringr::str_split:

df$Xflip <- sapply(stringr::str_split(df$X, ":"), function(x) 
    paste0(rev(x), collapse = ":"));

You can do the same using transform:

transform(df, Xflip = sapply(stringr::str_split(X, ":"), function(x) 
    paste0(rev(x), collapse = ":")))

The stringr::str_split method will also work if X contains a varying number of ":" separated entries.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

I'd split, flip, then concatenate. But there might be an easier way using mutate :)

flipper <- function(x){

    splitVector <- unlist(strsplit(x, ":")) #Split it by ":"
    flipVector <- rev(splitVector ) #Reverse it
    flipString <- paste0(flipVector, collapse = ":") #Paste it back together!
    return(flipString)

}

That should do the job for you!

Data$Xflip <- sapply(as.character(Data$X), flipper)
LachlanO
  • 1,152
  • 8
  • 14