Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum number in a character string (R)

Tags:

r

vector

sum

I have a vector that looks like :

numbers <- c("1/1/1", "1/0/2", "1/1/1/1", "2/0/1/1", "1/2/1")

(not always the same number of "/" character)

How can I create another vector with the sum of the numbers of each string?

Something like :

sum
3
3
4
4
4
like image 837
Arnaud Panes Avatar asked Jan 17 '18 10:01

Arnaud Panes


People also ask

How to find a sum of something in R?

You can use the sum() function in R to find the sum of values in a vector.


2 Answers

One solution with strsplit and sapply:

sapply(strsplit(numbers, '/'), function(x) sum(as.numeric(x)))
#[1] 3 3 4 4 4

strsplit will split your stings on / (doesn't matter how many /s you have). The output of strsplit is a list, so we iterate over it to calculate the sum with sapply.

like image 78
LyzandeR Avatar answered Sep 28 '22 18:09

LyzandeR


What seems to me to be the most straightforward approach here is to convert your number strings to actual valid string arithmetic expressions, and then evaluate them in R using eval along with parse. Hence, the string 1/0/2 would become 1+0+2, and then we can simply evaluate that expression.

sapply(numbers, function(x) { eval(parse(text=gsub("/", "+", x))) })

1/1/1   1/0/2 1/1/1/1 2/0/1/1   1/2/1 
    3       3       4       4       4 

Demo

like image 20
Tim Biegeleisen Avatar answered Sep 28 '22 19:09

Tim Biegeleisen