Baskerville
Baskerville

Reputation: 11

R: How can I Split and Trim Data Successfully

I've successfully split the data and removed the "," with the following code:

s = MSA_data$area_title str_split(s, pattern = ",")

    Result
    [1] "Albany" " GA"

I need to trim this data, removing white space, however this places the comma back into the data which was initially removed.

          "Albany, GA"

How can I successfully split and trim the data so that the result is:

[1] "Albany" "GA"

Thank you

Upvotes: 0

Views: 117

Answers (2)

akrun
akrun

Reputation: 887571

We just need to use zero or more spaces (\\s*) (the question OP asked) and this can be done in a single step

strsplit(MSA_data$area_title, pattern = ",\\s*")

If we are using the stringr, then make use of the str_trim

library(stringr)
str_trim(str_split("Albany, GA", ",")[[1]])
#[1] "Albany" "GA"    

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

An alternative is to use trimws function to trim the whitespace at the beginning and end of the string.

Result <- trimws(Result)

Upvotes: 1

Related Questions