[英]I have a vector whose elements contain multiple numbers. How do I sum numbers inside each element and create a new vector?
I have a vector of class 'factor'
like: 我有一个类'factor'
的向量:
vec <-c("1,1,1,1,1,2","2,1,2","3,3,4")
And I want to get another vector like this: 我想得到另一个这样的向量:
sumvec <- c(7, 5, 10)
How do I do this? 我该怎么做呢? I am using R. 我正在使用R。
Try this: 尝试这个:
> sapply(strsplit(as.character(vec), ","), function(x) sum(as.numeric(x)))
[1] 7 5 10
The basic idea is to split the character vector, extract the numeric values, and calculate the sum. 基本思想是分割字符向量,提取数值并计算总和。 strsplit
doesn't work on factors, so if you actually have factors, you'll need to convert them to characters first. strsplit
在要素上不起作用,因此,如果您确实有要素,则需要先将其转换为字符。 Similarly, sum
won't work on the resulting characters, so you need to convert that to numeric first. 同样, sum
不适用于结果字符,因此您需要先将其转换为数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.