thisisourconcerndude thisisourconcerndude - 24 days ago 7
R Question

Mystery 0 in Output of Pascal's Triangle Function in R

I'm trying to write a function in R that, given the

n
th row of Pascal's Triangle (in the form shown), it returns the
n+1
th row (in the same form).

I've written the function below and tested it for
n = 4
:

> pascal.tri <- function(n) {
+ l <- length(n)
+ for (i in 1:(l + 1)) {
+ new.vec[i] <- choose(l, (i - 1))
+ }
+ n[[l+1]] <- new.vec
+ return(n)
+ }
> n <- list(c(1), c(1, 1), c(1, 2, 1), c(1, 3, 3, 1))
> pascal.tri(n)
[[1]]
[1] 1

[[2]]
[1] 1 1

[[3]]
[1] 1 2 1

[[4]]
[1] 1 3 3 1

[[5]]
[1] 1 4 6 4 1 0


But I keep getting that random 0 appended to the
new.vec
(and so in the list). I've gone through this line by line, making it edits here and there, and it won't go away.

I have no idea what's causing this, so any help would be appreciated.

Answer Source

Your function gives another error: "Error in new.vec[i] <- choose(l, (i - 1)) : object 'new.vec' not found". This is because new.vec was not created before you use it within the scope of pascal.tri. By adding new.vec = c(), the error goes away.

pascal.tri <- function(n) {
       new.vec = c()
       l <- length(n)
       for (i in 1:(l + 1)) {
             new.vec[i] <- choose(l, (i - 1))
         }   
       n[[l+1]] <- new.vec
       return(n)
}

n <- list(c(1), c(1, 1), c(1, 2, 1), c(1, 3, 3, 1))

pascal.tri(n)

Result:

[[1]]
[1] 1

[[2]]
[1] 1 1

[[3]]
[1] 1 2 1

[[4]]
[1] 1 3 3 1

[[5]]
[1] 1 4 6 4 1

Not able to reproduce your other error