Extract all numbers from a single string in R

后端 未结 4 1146
夕颜
夕颜 2020-11-30 07:54

Let\'s imagine you have a string:

strLine <- \"The transactions (on your account) were as follows: 0 3,000 (500) 0 2.25 (1,200)\"

Is the

4条回答
  •  爱一瞬间的悲伤
    2020-11-30 08:10

    library(stringr)
    x <- str_extract_all(strLine,"\\(?[0-9,.]+\\)?")[[1]]
    > x
    [1] "0"       "3,000"   "(500)"   "0"       "2.25"    "(1,200)"
    

    Change the parens to negatives:

    x <- gsub("\\((.+)\\)","-\\1",x)
    x
    [1] "0"      "3,000"  "-500"   "0"      "2.25"   "-1,200"
    

    And then as.numeric() or taRifx::destring to finish up (the next version of destring will support negatives by default so the keep option won't be necessary):

    library(taRifx)
    destring( x, keep="0-9.-")
    [1]    0 3000  -500    0    2.25 -1200
    

    OR:

    as.numeric(gsub(",","",x))
    [1]     0  3000  -500     0     2.25 -1200
    

提交回复
热议问题