【问题标题】:Drop a word in a column of data table in R在R中的数据表列中删除一个单词
【发布时间】:2019-08-31 03:00:55
【问题描述】:

我有一个看起来像这样的数据表

            location                county
1:  40.96875_-72.78125      Walla Walla County
2:  41.15625_-90.65625           Mercer County
3:  41.21875_-90.65625           Mercer County
4:  41.28125_-89.84375           Bureau County
5:  41.28125_-89.90625            Henry County

我怎样才能有效地在county 列中删除“县”一词,所以那里只留下县的名称。

【问题讨论】:

    标签: r dataframe datatable


    【解决方案1】:

    我们可以使用sub选择一个或多个空格后跟直到字符串结尾($)不是空格的字符,替换为空格("")

    dt1[, county := sub("\\s+[^ ]+$", "", county)]
    dt1$county
    #[1] "Walla Walla" "Mercer"      "Mercer"      "Bureau"      "Henry"      
    

    如果它是特定于“县”字的,那么

    dt1[, county := sub("\\s+County$", "", county)]
    

    【讨论】:

      【解决方案2】:

      或者,您可以使用 de gsub 函数,将单词 "county" 替换为 "":

      df$county = gsub("county", "", df$county)
      

      【讨论】:

        猜你喜欢
        • 2021-10-23
        • 2021-02-03
        • 2018-04-04
        • 2018-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        • 2018-01-08
        相关资源
        最近更新 更多