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
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
in your particular case (2 numbers):
as.integer(a[[1]][1]) + as.integer([[1]][2])
More generally:
sum(sapply(a[[1]], as.integer))
or from your list, after parsing:
sapply(a, function(x) sum(as.numeric(x)))