Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a number in R

Tags:

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.

like image 531
dplanet Avatar asked Oct 09 '12 19:10

dplanet


1 Answers

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.

like image 81
Gavin Simpson Avatar answered Oct 14 '22 17:10

Gavin Simpson