R remove last word from string

后端 未结 2 1087
误落风尘
误落风尘 2020-12-03 17:34

I\'m trying to do something but can\'t remember/find the answer. I have a list of city names from the Census Bureau and they put the city\'s type on the end which is messin

相关标签:
2条回答
  • 2020-12-03 18:02

    This will work:

    gsub("\\s*\\w*$", "", df1$city)
    [1] "Middletown"   "Sunny Valley" "Hillside"   
    

    It removes any substring consisting of one or more space chararacters, followed by any number of "word" characters (spaces, numbers, or underscores), followed by the end of the string.

    0 讨论(0)
  • 2020-12-03 18:08

    Here's a regexp that does what you need:

    sub(df1$city, pattern = " [[:alpha:]]*$", replacement = "")
    

    [1] "Middletown" "Sunny Valley" "Hillside"

    That's replacing a substring that starts with a space, then contains only letters until the end of the string, with an empty string.

    0 讨论(0)
提交回复
热议问题