Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R sum() Function - Calculating the Sum

R sum() Function - Calculating the Sum

R Language Examples R Language Examples

The R sum() function is used to calculate the sum of all elements in a vector or matrix.

When doing summary statistics on data, sum() is one of the most commonly used functions.

The syntax of the sum() function is as follows:

sum(x, na.rm = FALSE)

Parameter Description:

Example

Create a vector

x

<-

c

(

12

,

27

,

3

,

4.2

,

2

,

2

,

54

,

21

,

4

,

2

)

Calculate the total

result.

sum

<-

sum

(

x

)

print

(

result.

sum

)

The output of the code above is:

[1] 85.2

When a vector contains missing values NA, if na.rm = TRUE is not set, sum() returns NA:

Example

A vector containing NA

x

<-

c

(

10

,

20

, NA,

30

,

40

)

Without handling NA, the result is NA

result.

na

<-

sum

(

x

)

print

(

result.

na

)

Set na.rm = TRUE to ignore NA

result.

ok

<-

sum

(

x, na.

rm

=

TRUE

)

print

(

result.

ok

)

The output of the code above is:

[1] NA

[1] 100

R Language Examples R Language Examples