2

While working on a small program for calculating the right triangular number that fulfils an equation, I stumbled over a page that holds documentation on the function Triangular() Triangular function

When I tried to use this, Rstudio says it couldn't find it and I can't seem to find any other information about what library this could be in.

Does this function even exist and/or are there other ways to fill a vector with triangular numbers?

Djaff
  • 173
  • 1
  • 10

2 Answers2

2
  • Here is a base R solution to define your custom triangular number generator, i.e.,
myTriangular <- function(n) choose(seq(n),2)

or

myTriangular <- function(n) cumsum(seq(n)-1)

such that

> myTriangular(10)
 [1]  0  1  3  6 10 15 21 28 36 45
  • If you would like to use Triangular() from package Zseq, then please try
Zseq::Triangular(10)

such that

> Zseq::Triangular(10)
Big Integer ('bigz') object of length 10:
 [1] 0  1  3  6  10 15 21 28 36 45
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Thank you, this solves my problem perfectly! Is there a performance difference between the two solutions? – Djaff Jan 27 '20 at 14:08
  • 1
    @Esye I did not compared their performance in terms of speed...but `Zseq::Triangular` seems able to deal with super large numbers, which might be tough for the base R solution. – ThomasIsCoding Jan 27 '20 at 14:11
0

It's pretty easy to do it yourself:

triangular <- function(n) sapply(1:n, function(x) sum(1:x))

So you can do:

triangular(10)
# [1]  1  3  6 10 15 21 28 36 45 55
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87