Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we split an integer number into a vector of its constituent digits in R

I think an example should make things clear enough.

I have

a_1 = 6547

and I want some function that transform a_1 into the following a_2

a_2 = c(6, 5, 4, 7)

like image 398
Remi.b Avatar asked Nov 04 '13 08:11

Remi.b


3 Answers

Convert to character then split will do the trick

a <- 6547
as.numeric(strsplit(as.character(a), "")[[1]])
## [1] 6 5 4 7
like image 195
CHP Avatar answered Nov 15 '22 08:11

CHP


(a %% c(1e4, 1e3, 1e2, 1e1)) %/% c(1e3, 1e2, 1e1, 1e0)

This is 3-4x as fast on my computer than doing a strsplit. But the strsplit is a lot more elegant and the difference decreases with longer vectors.

library(microbenchmark)
microbenchmark((a %% c(1e4, 1e3, 1e2, 1e1)) %/% c(1e3, 1e2, 1e1, 1e0))
# median of 1.56 seconds
microbenchmark(as.numeric(strsplit(as.character(a), "")[[1]]))
# median of 8.88 seconds

Edit: using Carl's insight, here is a more general version.

a <- 6547
dig <- ceiling(log10(a))
vec1 <- 10^(dig:1)
vec2 <- vec1/10
(a%%vec1)%/%vec2
like image 22
Anirban Avatar answered Nov 15 '22 09:11

Anirban


This also works. It's slower than the other answers, but possibly easier to read...

library(stringr)
as.integer(unlist(str_split(a, "")))[-1]
like image 45
dardisco Avatar answered Nov 15 '22 09:11

dardisco