Harry Moreno
Harry Moreno

Reputation: 11613

Why does R fail to evaluate this line?

R fails to evaluate at line 15. Could someone tell me why it fails? This is a simple program that makes all products of numbers of length 3. Then finds the largest of these that is a palindrome number, e.g., 9009.

largestpalndrome3 <- function(){
products3 <- c()
i <- 100
while(i <= 999){
    j <- i
    while(j <= 999){
        products3[i] <- i*j
        j <- j+1
    }
    i <- i+1
}
palindromes <- c()
i <- 1
for(prod in products3){
    if(prod<100000){
        prodcopy <- prod
        o <- prodcopy %% 10
        prodcopy = prodcopy%/%10
        t <- prodcopy %% 10
        prodcopy = prodcopy%/%10
        h <- prodcopy %% 10
        prodcopy = prodcopy%/%10
        th <- prodcopy %% 10
        prodcopy = prodcopy%/%10
        tth <- prodcopy %% 10
        hth <- prodcopy%/%10
        if(o==hth & t==tth & h==th){
            palindromes[i] <- prod
        }
    }
    if(prod>100000){
        prodcopy <- prod
        o <- prodcopy %% 10
        prodcopy = prodcopy%/%10
        t <- prodcopy %% 10
        prodcopy = prodcopy%/%10
        h <- prodcopy %% 10
        prodcopy = prodcopy%/%10
        prodcopy = prodcopy%/%10
        tth <- prodcopy %% 10
        prodcopy = prodcopy%/%10
        hth <- prodcopy%%10
        m <- prodcopy%/%10
        if(o==m & t==hth & h==tth){
            palindromes[i] <- prod
        }
    }
    i <- i + 1
}
}

Upvotes: 1

Views: 171

Answers (2)

Ram Narasimhan
Ram Narasimhan

Reputation: 22506

The reason you are getting the error is that in the way you have defined product3, the first 99 elements of it are NA.

Before using a value, you have to perform a check. One simple step is to use the is.na() check.

Here's a small change that first checks whether prod is NA and proceeds if it isn't. This will get you past your error.

for(prod in products3){

        if(!is.na(prod)) {
            ...
            your code here
            ...
        }
    }

@AndresT gives you a different (and more efficient) way to do what you are attempting.

Upvotes: 2

aatrujillob
aatrujillob

Reputation: 4826

This would solve your problem:

palindromes = function(n=3){

A1 = c((10^n-1):10^(n-1))
A2 = as.character(A1)


ltrs= sapply(A2,substring,1:n,1:n)
rownames(ltrs)=c(1:n)
ltrs=  ltrs[order(rownames(ltrs),decreasing=T),]
ltrs= apply(ltrs,2,paste,collapse='')


A2 = as.numeric(paste(A2,ltrs,sep=''))

A3= combn((10^n-1):10^(n-1),2)
A4 = A3[1,]*A3[2,]

largestpal = max(A2[ A2 %in% A4])

prod2= A3[,which(A4==largestpal)]

return(list('Number of Digits'=n, 'Largest Palindrome'=largestpal,'multiple of'=prod2))

}

Upvotes: 3

Related Questions