Search code examples
rintegerdigits

R: number of items to replace is not a multiple of replacement


I am trying to split 2009 into 2 0 0 9.

int2v<-function(n){
+ digits<-floor(log10(n))+1
+ i<-1
+ repeat{
+ n[i]<-n%%10^(digits-i+1)%/%10^(digits-i)
+ i<-i+1
+ if(i>digits) break
+ }
+ n
+ }

> int2v(2009)
[1] 2 0 0 2
Warning messages:
1: In n[i] <- n%%10^(digits - i + 1)%/%10^(digits - i) :
  number of items to replace is not a multiple of replacement length
2: In n[i] <- n%%10^(digits - i + 1)%/%10^(digits - i) :
  number of items to replace is not a multiple of replacement length

I cannot get the answer 2 0 0 9 but have some warning message. But I can't think of any mistakes in the function. so, can any one help me? Thanks a lot.


Solution

  • Using your code

    int2v<-function(n){
     digits<-floor(log10(n))+1
     i<-1
     n1 <- c()
     repeat{
      n1<-c(n1,n%%10^(digits-i+1)%/%10^(digits-i))
      i<-i+1
     if(i>digits) break
      }
     n1
     }
    
    
    int2v(2009)
    #[1] 2 0 0 9
    
    int2v(20)
    #[1] 2 0