Character Number Amount (R)

I have a vector that looks like this:

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

(not always the same number "/")

How to create another vector with the sum of the numbers of each line?

Sort of:

sum
3
3
4
4
4
+4
source share
3 answers

One solution with strsplitand sapply:

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

strsplitwill divide your sting into /(no matter how much you have /). The output strsplitis a list, so we iterate over it to calculate the sum with sapply.

+2
source

, - , R, eval parse. , 1/0/2 1+0+2, .

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 

+2

1) strapply strapply \\d+, as.numeric , . sum . .

library(gsubfn)

sapply(strapply(numbers, "\\d+", as.numeric), sum)
## [1] 3 3 4 4 4

2) read.table . ( ), .

sapply(numbers, function(x) sum(read.table(text = x, sep = "/")))
##   1/1/1   1/0/2 1/1/1/1 2/0/1/1   1/2/1 
##       3       3       4       4       4 

USE.NAMES = FALSE sapply, .

scan(textConnection(x), sep = "/", quiet = TRUE) read.table, .

0

Source: https://habr.com/ru/post/1692303/


All Articles