【问题标题】:How to suppress blank space before a value [duplicate]如何在值之前抑制空格[重复]
【发布时间】:2021-03-04 23:34:15
【问题描述】:
Country<-c(" Germany"," France", "Greece"," United-State", "Spain")
Country

例如GermanyFranceUnited-State之前有空格

[1] " Germany"      " France"       "Greece"        " United-State" "Spain"

我想取消国家名称前的所有空格,以便有这样的:

[1] "Germany"      "France"       "Greece"        "United-State" "Spain"

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用base R 中的trimws(不使用任何包)

    Country <- trimws(Country)
    Country
    #[1] "Germany"      "France"       "Greece"       "United-State" "Spain"       
    

    或者sub

    sub("^\\s+", "", Country)
    

    【讨论】:

      【解决方案2】:

      这是一个使用stringr 包中的str_trim 的解决方案,以便从字符串的开头和结尾删除空格。

      代码:

      library(stringr)
      
      Country<-c(" Germany"," France", "Greece"," United-State", "Spain")
      
      str_trim(Country)
      

      输出:

      [1] "Germany"      "France"       "Greece"       "United-State" "Spain"
      

      原文:

      [1] " Germany"      " France"       "Greece"        " United-State" "Spain"    
      

      reprex package (v0.3.0) 于 2020 年 11 月 21 日创建

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-05
        • 2014-11-12
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 2021-11-03
        相关资源
        最近更新 更多