【问题标题】:How to Reverse the delimited parts of a string [duplicate]如何反转字符串的分隔部分[重复]
【发布时间】:2018-03-06 22:42:22
【问题描述】:

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

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

谢谢!

【问题讨论】:

  • 我很抱歉——我上面的例子中有一些错别字。我将编辑我的示例。感谢您到目前为止的回复。
  • 我不清楚这是完全重复的,因为我需要反转分隔字符串的部分而不是字符串中的每个字符。我编辑了标题以反映这种差异。我注意到在“如何在 R 中反转字符串”文章中执行了 strsplit,但使用 NULL 作为分隔符 - 不知道为什么。

标签: r hierarchy concat


【解决方案1】:

或者使用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 方法也将起作用。

【讨论】:

  • 感谢您的帮助。我显然有更多关于 R 编程的知识。你启发了我更多地“挖掘”。
  • 不用担心@A.Maffei;很高兴我能帮上忙。如果答案有用,请考虑投票。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多