# Creating a sequence

Hi I'm just learning to use rstudio and need help creating a sequence of the first 20 triangular numbers using the equation n*(n+1)/2. Thanks!

Hi @graceel! Give this a crack:

``````n <- 1:20
tri_nums <- n * (1 + 1) / 2
``````

(The `:` operator generates regular sequences in intervals of 1, so the first statement there is just generating a vector from 1 to 20.)

If you're feeling adventurous, you can put combine the statements like:

``````# i mean, i guess (1:20) + 1 is just 2:21
tri_nums <- (1:20) * ((1:20) + 1) / 2
``````

If you use the colon operator inside of a larger statement this way, I'd urge you to be careful and (wrap it in parentheses): some operators have a different precedence (in particular `-` and `+` depending on how they're read), and you might end up with a confusing bug! Hope that helps So, based on how you state your question, I'm going to spell it out ``````# Define the numbers we are going to work on
n = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

# Create empty vector to hold the results
tri_nums = c()

# Loop over each number in n, calculate and append corresponding triangular number
for( n_i in n ){
tri_nums = append(tri_nums, n_i * (n_i + 1) / 2)
}
``````

We can simplify this a bit, by using the `seq()` function, recall we can get help on a function by typing `?seq`

``````# See help on seq function
?seq

# Define the numbers we are going to work on
n = seq(from = 1, to = 20, by = 1)

# Create empty vector to hold the results
tri_nums = c()

# Loop over each number in n, calculate and append corresponding triangular number
for( n_i in n ){
tri_nums = append(tri_nums, n_i * (n_i + 1) / 2)
}
``````

Now, du to vectorisation, `R` actually let's us skip the loop, like so:

``````# Define the numbers we are going to work on
n = seq(from = 1, to = 20, by = 1)

# Create empty vector to hold the results
tri_nums = c()

# Loop over each number in n, calculate and append corresponding triangular number
tri_nums = n * (n + 1) / 2
``````

Finally, we use the `seq(by = 1)` short hand `from:to` and since `R` does not require us to define variables prior to assignment, we get the following:

``````# Define the numbers we are going to work on
n = 1:20

# Loop over each number in n, calculate and append corresponding triangular number
tri_nums = n * (n + 1) / 2
``````

We can compress this even further by simply defining the sequence, inside the expression for calculating the triangular numbers:

``````# Define the numbers we are going to work on
# Create empty vector to hold the results
# Loop over each number in n, calculate and append corresponding triangular number
tri_nums = 1:20 * (1:20 + 1) / 2
``````

So, basically vectorisation for the win!

Hope it helps Leon

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.