YouTip LogoYouTip

R Func Sum

# R sum() Function - Calculate Sum [![Image 3: R Language Examples](https://example.com/images/up.gif) R Language Examples](https://example.com/r/r-examples.html) The R sum() function is used to calculate the sum of all elements in a vector or matrix. When performing summary statistics on data, sum() is one of the most commonly used functions. The sum() function syntax is as follows: sum(x, na.rm = FALSE) **Parameter Description:** * **x** Input vector, matrix, or data frame column. * **na.rm** Boolean value, default is FALSE, sets whether to remove missing values NA. Set to TRUE to ignore NA when calculating the sum. ## Example # Create a vector x <-c(12, 27, 3, 4.2, 2, 2, 54, -21, 4, -2) # Calculate sum result.sum<-sum(x) print(result.sum) The output of executing the above code is: 85.2 When the vector contains missing values NA, if na.rm = TRUE is not set, sum() will return NA: ## Example # Vector with NA x <-c(10, 20, NA, 30, 40) # Not handling NA, result is NA result.na<-sum(x) print(result.na) # Set na.rm = TRUE, ignore NA result.ok<-sum(x, na.rm= TRUE) print(result.ok) The output of executing the above code is: NA 100 [![Image 4: R Language Examples](https://example.com/images/up.gif) R Language Examples](https://example.com/r/r-examples.html)
← R Func T TestR Func Subset β†’