Get startedGet started for free

For loops continued...

Now we are going to compute the sum of the squares for several values of \(n\). We will use a for-loop for this. Here is an example of a for-loop:

results <- vector("numeric", 10)
n <- 10
for(i in 1:n){
    x <- 1:i
    results[i] <- sum(x)
}

Note that we start with a call to vector which constructs an empty vector that we will fill while the loop runs.

This exercise is part of the course

Data Science R Basics

View Course

Exercise instructions

  • Define an empty numeric vector s_n of size 25 using s_n <- vector("numeric", 25).
  • Compute the the sum when n is equal to each integer from 1 to 25 using the function we defined in the previous exercise: compute_s_n
  • Save the results in s_n

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define a function and store it in `compute_s_n`
compute_s_n <- function(n){
  x <- 1:n
  sum(x^2)
}

# Create a vector for storing results
s_n <- vector("numeric", 25)

# write a for-loop to store the results in s_n
Edit and Run Code