【问题标题】:How to get the text after the last comma?如何获取最后一个逗号后的文本?
【发布时间】:2019-02-19 10:27:54
【问题描述】:

我有一条短信,说:

s <- "Chengdu Shi, Sichuan Sheng, China"

我想使用一个函数,这样我只会得到最后一个逗号之后的单词(即中国)。

我尝试了几种方法,例如 grep,但它们返回所有实例而不是最后一个。

【问题讨论】:

  • 到目前为止你有什么尝试?
  • dplyr() 中查看last(),或者在base r 中,使用length() 访问向量的最后一项

标签: r substring


【解决方案1】:

使用sub

# Simply get the text after last comma ,
sub('.*\\,', '', s)

使用来自library(stringr) 包的word

s <- "Chengdu Shi, Sichuan Sheng, China"
word(s,3,sep=",") # Extract word from the last column

# If your data is stored in data.frame
word(s,ncol(s),sep=",") # Extract last column data using column index

输出:

[1] " China"

【讨论】:

    【解决方案2】:

    试试:

    sapply(strsplit(s,", "),"[")[3]
    [1] "China"
    

    【讨论】:

      【解决方案3】:
      Use stringi package
      
         s <- "Chengdu Shi, Sichuan Sheng, China"
      
          library(stringi)
      
          stri_extract_last_words(s)
          [1] "China"
      

      【讨论】:

        【解决方案4】:

        试试:

        wordAfterLastComma <- function(x, sep = ","){
          x <- sapply(strsplit(x, sep),"[")
          trimws(x[[length(x)]])
        }
        
        s1 <- "Chengdu Shi, Sichuan Sheng, China"
        s2 <- "Chengdu Shi, Sichuan Sheng, China,Chengdu Shi"
        
        wordAfterLastComma(s1)
        # [1] "China"
        
        wordAfterLastComma(s2)
        # [1] "Chengdu Shi"
        

        【讨论】:

          猜你喜欢
          • 2012-03-19
          • 2021-11-28
          • 2015-12-10
          • 1970-01-01
          • 1970-01-01
          • 2021-11-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多