markdjthomas
markdjthomas

Reputation: 115

Convert a vector of integers into a single number

Does anyone know a way to turn a vector of integers into a single number in R, for example:

> x <- c(1,2,3)
> x <- compress(x)
> x
[1] 123

Where compress() would be some sort of function to do so. I would like the value x to be a single number so I can multiply it by an encryption key.

Upvotes: 2

Views: 4060

Answers (2)

MrFlick
MrFlick

Reputation: 206243

When we write a number 123 that's the same as

1*10^2 + 2*10^1 + 3*10^0

so you can also do

x <- c(1,2,3)
sum(x * 10^((length(x)-1):0))
# [1] 123

Upvotes: 1

Fernando
Fernando

Reputation: 7895

Try this

x = 1:3
as.numeric(paste(x, collapse = ""))
# 123

Upvotes: 7

Related Questions