Search code examples
rstringrreadr

splitting text into character and numeric


Could someone help me split this string:

string <- "Rolling in the deep    $15.25"

I'm trying to get two outputs out of this:

1) Rolling in the Deep  # character
2) 15.25                # numeric value

I know how to do this in excel but a bit lost with R


Solution

  • Using strsplit will do the trick. The solution will be as:

    string <- "Rolling in the deep    $15.25"
    
    strsplit(string, "\\s+\\$")
                        ^   ^___ find a $ (escaped with \\ because $ means end of word)
                         \______ find 1 or more whitespaces
    # Result
    #"Rolling in the deep" "15.25"
    
    strsplit(string, "\\s+\\$")[[1]][1]
    #[1] "Rolling in the deep"
    
    strsplit(string, "\\s+\\$")[[1]][2]
    #[1] "15.25"