R:如何将列表分成几个数字并进行计算? [英] R: How to split list into several numbers and do the calculation?
本文介绍了R:如何将列表分成几个数字并进行计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据就像: -3 + 2 41-12 使用以下代码分离每个部分之后: 例如.
my data is like: -3+2 41-12 after separating each part by using the following code: eg.
text = '-3+2'
pattern = '-?\\d+'
matches = gregexpr(pattern, text)
a=regmatches(text, matches)
我有一个数字"列表
a
[[1]]
[1] "-3" "2"
如果我想将-3和2加在一起怎么办?例如(-3 + 2)=-1 因为上面的结果是一个列表,所以as.numeric不起作用... 非常感谢!
what if i want to add -3 and 2 together? eg(-3+2)=-1 because the result above is a list, so as.numeric does not work... many many thanks!
推荐答案
我通常知道这是不好的形式,但是我认为最简单的方法是在这些情况下使用eval
和parse
并完全跳过正则表达式:
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
这篇关于R:如何将列表分成几个数字并进行计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文