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

后端 未结 3 693
北恋
北恋 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
    
    0 讨论(0)
  • 2021-01-26 08:08

    in your particular case (2 numbers):

    as.integer(a[[1]][1]) + as.integer([[1]][2])

    More generally:

    sum(sapply(a[[1]], as.integer))

    0 讨论(0)
  • 2021-01-26 08:22

    or from your list, after parsing:

    sapply(a, function(x) sum(as.numeric(x)))
    
    0 讨论(0)
提交回复
热议问题