How to reverse a sentence in R?

大兔子大兔子 提交于 2019-12-01 16:42:25

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"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!