thisisourconcerndude - 5 months ago 25

R Question

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

`n`

`n+1`

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`

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**