如何反转字符串的分隔部分

How to Reverse the delimited parts of a string

我正在尝试反转在数据框中找到的分层名称的部分,以便我可以使用反向路径的字符串。这是我所做的:

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

谢谢!

我会拆分、翻转,然后连接。但是使用 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)

}

这应该适合你!

Data$Xflip <- sapply(as.character(Data$X), flipper)

或使用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

或使用stringr::str_split:

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

您可以使用 transform:

来做同样的事情
transform(df, Xflip = sapply(stringr::str_split(X, ":"), function(x) 
    paste0(rev(x), collapse = ":")))

如果 X 包含不同数量的 ":" 分隔条目,stringr::str_split 方法也将起作用。