简体   繁体   English

我有一个向量,其元素包含多个数字。 如何对每个元素中的数字求和并创建新的向量?

[英]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.

相关问题 我如何创建一个向量,其分量是 x 的幂数,并且随着数字的增长,指数 x 逐渐减小 - How can i create a vector whose components are numbers in the power of x and as the number grows the exponent x gradually decreases 如何对元素包含字母和数字的字符向量进行排序? - How to sort a character vector where elements contain letters and numbers? 如何对 R 中元素包含数字和字母的字符向量进行排序? - How to sort a character vector where elements contain numbers and letters in R? 如何在 R 中获取数字向量的元素,并创建一个包含 seq 从 1:(每个元素)的新向量 - How to take elements of a numeric vector in R, and create a new vector containing seq from 1:(each element) 如何将数值向量转换为二进制数? - How do I convert a numeric vector into binary numbers? 如何按升序对包含许多数字字符串的向量进行排序? - How do I sort a vector with many strings of numbers in ascending order? 如何在R中的向量中找到连续数字的范围 - How do I find ranges of successive numbers in a vector in R 在 R 中,如何创建一个函数,其中向量中的所有数字都重新缩放,Inf 变为 1,-Inf 变为 0? - In R, how do I create a function where all the numbers in a vector are rescaled, Inf becomes 1, and -Inf becomes 0? 如何确定向量中有多少元素包含来自第二个向量的模式? - How do I determine how many elements in a vector contain a pattern from a second vector? 向向量的每个元素添加两个数字 - Add two numbers to each element of a vector
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM