dplanet
dplanet

Reputation: 5403

Splitting a number in R

In R I have a number, say 1293828893, called x.

I wish to split this number so as to remove the middle 4 digits 3828 and return them, pseudocode is as follows:

splitnum <- function(number){
     #check number is 10 digits
     if(nchar(number) != 10){
          stop("number not of right size");
     }
     middlebits <- middle 4 digits of number
     return(middlebits);
}

This is a pretty simple question but the only solutions I have found apply to character strings, rather than numeric ones.

If of interest, I am trying to create an implementation in R of the Middle-square method, but this step is particularly tricky.

Upvotes: 6

Views: 1374

Answers (3)

Gavin Simpson
Gavin Simpson

Reputation: 174813

You can use substr(). See its help page ?substr. In your function I would do:

splitnum <- function(number){
    #check number is 10 digits
    stopifnot(nchar(number) == 10)
    as.numeric(substr(number, start = 4, stop = 7))
}

which gives:

> splitnum(1293828893)
[1] 3828

Remove the as.numeric(....) wrapping on the last line you want the digits as a string.

Upvotes: 9

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

Here's a function that completely avoids converting the number to a character

splitnum <- function(number){
     #check number is 10 digits
     if(trunc(log10(X))!=9) {
          stop("number not of right size")
     }
     (number %/% 1e3) %% 1e4
}

splitnum(1293828893)
# [1] 3828

Upvotes: 6

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

Just use integer division:

> x <- 1293828893
> (x %/% 1e3) %% 1e4
[1] 3828

Upvotes: 8

Related Questions