sum(): Sum up values in a vector

The function sum is a widely used function to sum up the values in a vector, data.frame. An argument na.rm is used to ignore NA values when the vector has NA values.

The basic usage of sum() function is written in the exercise.

Instruction

  • Click the Submit button.
  • See what happens in the console and put na.rm argument in sum function to fix line 14.
# Generate a vector from 1 to 10 x <- seq(1, 10) # Sum up the values in variable x sum(x) # Generate a vector that includes NA value y <- c(seq(1,5), NA, seq(6,10)) # print y y # Fix the following code by using na.rm argument to remove NA when calculating sum. z <- sum(y) z # Generate a vector from 1 to 10 x <- seq(1, 10) # Sum up the values in variable x sum(x) # Generate a vector that includes NA value y <- c(seq(1,5), NA, seq(6,10)) # print y y # Fix the following code by using na.rm argument to remove NA when calculating sum. z <- sum(y, na.rm=TRUE) z msg <- "Please see that objects are well-defined and correct." test_object("x", undefined_msg = msg, incorrect_msg = msg) test_object("y", undefined_msg = msg, incorrect_msg = msg) test_object("z", undefined_msg = msg, incorrect_msg = msg) success_msg("Great! Head over to the next exercise.")

Previous: 1-12 | rep(): replicate elements of vectors and lists

Next: 1-14 | max(), min(): Maxima and Minima

Back to Main