How to reverse a sentence in R?

后端 未结 1 1140
逝去的感伤
逝去的感伤 2021-01-18 02:04

I want a function that takes a string (NOT a vector) and reverses the words in that string.

For example,

rev_sentence(\"hi i\'m five\")
## [1] \"five         


        
相关标签:
1条回答
  • 2021-01-18 02:16

    In R, We can use strsplit to split at one or more spaces and then reverse the elements and paste it together

    sapply(strsplit(str1, "\\s+"), function(x) paste(rev(x), collapse=" "))
    #[1] "five i'm hi"
    

    If there is only a single string, then

    paste(rev(strsplit(str1, "\\s+")[[1]]), collapse= " ")
    #[1] "five i'm hi"
    

    In Python, the option would be to split and join after reversing ([::-1])

    " ".join("hi i'm five".split()[::-1])
    #"five i'm hi"
    

    Or use the reversed

    " ".join(reversed("hi i'm five".split()))
    #"five i'm hi"
    

    data

    str1 <- "hi i'm five"
    
    0 讨论(0)
提交回复
热议问题