R: How to split list into several numbers and do the calculation?

后端 未结 3 747
北恋
北恋 2021-01-26 07:42

my data is like: -3+2 41-12 after separating each part by using the following code: eg.

text = \'-3+2\'

pattern = \'-?\\\\d+\'
matches = gre         


        
3条回答
  •  灰色年华
    2021-01-26 08:08

    I know it's bad form in general, but I think the simplest approach is to use eval and parse in these cases and completely skip the regex:

    text = c("-3+2", "99+44-100")
    sapply(text, function(x) eval(parse(text=x)))
    #      -3+2 99+44-100 
    #        -1        43 
    

    If you dislike the names on the vectors you can instead do:

    unname(sapply(text, function(x) eval(parse(text=x))))
    # [1] -1 43
    

提交回复
热议问题