0

I'm trying to obtain the following exact output.enter image description here

Below is first what I initially tried and then what I saw while attempting to find a solution.

 if(i<- 10) {choose(i, 0:10)}
  [1]   1  10  45 120 210 252 210 120  45  10   1

pascalTriangle <- function(h) {
  lapply(0:h, function(i) choose(i, 0:i))
}
> pascalTriangle(10)
[[1]]
[1] 1

[[2]]
[1] 1 1

[[3]]
[1] 1 2 1

... etc.

The second code gets the right numbers, but the formatting is way off and I'm stumped on how I could go about tweaking the code to obtain my desired output. If I'm missing any information you need please let me know

redwoods
  • 59
  • 5
  • 1
    Does this answer your question? [How would you program Pascal's triangle in R?](https://stackoverflow.com/questions/2632441/how-would-you-program-pascals-triangle-in-r) See the accepted answer. – Peter Mar 24 '22 at 17:44

1 Answers1

1

You could do:

pascalTriangle <- function(h) {
  li <- lapply(lapply(0:h, function(i) choose(i, 0:i)), 
               function(i) paste(stringr::str_pad(i, 4, 'both'), collapse = ''))
  li <- lapply(seq_along(li), function(i) {
    cat(paste0(paste(rep(' ', 2 *(length(li) - i)), collapse = ''), li[[i]]), 
        sep = '\n')
  })
}

Which results in

pascalTriangle(10)
                     1  
                   1   1  
                 1   2   1  
               1   3   3   1  
             1   4   6   4   1  
           1   5   10  10  5   1  
         1   6   15  20  15  6   1  
       1   7   21  35  35  21  7   1  
     1   8   28  56  70  56  28  8   1  
   1   9   36  84 126 126  84  36  9   1  
 1   10  45 120 210 252 210 120  45  10  1  
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87