How to Reverse a string in R

后端 未结 14 2079
花落未央
花落未央 2020-11-27 03:29

I\'m trying to teach myself R and in doing some sample problems I came across the need to reverse a string.

Here\'s what I\'ve tried so far but the paste operation d

14条回答
  •  清歌不尽
    2020-11-27 04:09

    Here's a solution with gsub. Although I agree that it's easier with strsplit and paste (as pointed out in the other answers), it may be interesting to see that it works with regular expressions too:

    test <- "greg"
    
    n <- nchar(test) # the number of characters in the string
    
    gsub(paste(rep("(.)", n), collapse = ""),
         paste("", seq(n, 1), sep = "\\", collapse = ""),
         test)
    
    # [1] "gerg"
    

提交回复
热议问题