ericanita
ericanita

Reputation: 13

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.

Upvotes: 1

Views: 553

Answers (2)

akrun
akrun

Reputation: 887951

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

Upvotes: 0

Will Scott
Will Scott

Reputation: 142

This can actually be done via built-in functions:

n<-2009
as.numeric(unlist(strsplit(as.character(n),"")))
[1] 2 0 0 9

as.character converts the number n into a character string. strsplit splits the resulting string, with the second argument to strsplit making this split happen at every character. unlist collapses the list produced by strsplit into a vector, and as.numeric converts back to a numeric (rather than character) vector.

This won't work (obviously!) if n is not numeric to begin with ... you might want to test for this pre-condition if you wrap this code in a function. It's also worth noting that this won't work with a vector of numbers in n, because the unlist will collapse them all into one character string. But extending to these cases (if they are needed) shouldn't be too hard.

Upvotes: 2

Related Questions