How do I change a vector into a single number

Viewed 208

Lets say I have a vector x which is

x = c(1,2,3,4,5)

and I want it to have a single length of all the numbers in the vector so that the end result looks like this:

x = 12345

If I then want to example multiply it by 2 it would show: 12345*2 = 24690

Instead of: 1,2,3,4,5 * 2 = 2,4,6,8,10

Any easy way to do it?

4 Answers

Another option with Reduce()

as.numeric(Reduce(paste0, x))
# [1] 12345

Maybe you can try

> sum(x*10**rev(seq_along(x)-1))*2
[1] 24690

or the variation by @Roland

> 2 * x %*% (10 ^ rev(seq_along(x)) / 10
[1] 24690

or define function f like below

f <- function(x, l = length(x)) ifelse(l==1,x,f(x[1:(l-1)],l-1)*10 + x[l])
> f(x)*2
[1] 24690

or play a trick with paste + as.numeric

> as.numeric(paste(x,collapse = ""))*2
[1] 24690

You can use nchar and cumprod to get the digits, rev to reverse them and %*% to multiply and sum it.

rev(x) %*% cumprod(c(1, 10^nchar(rev(x[-1]))))
#      [,1]
#[1,] 12345

rev(x) %*% cumprod(c(1, 10^nchar(rev(x[-1])))) * 2
#      [,1]
#[1,] 24690

And for more than 1 digit:

x <- c(1, 22, 333)
rev(x) %*% cumprod(c(1, 10^nchar(rev(x[-1]))))
#       [,1]
#[1,] 122333

using paste with collapse

as.numeric( paste(x, collapse=''))
#[1] 12345
Related