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

R mean() Function - Calculating the Average

R mean() Function - Calculating the Average

R Language Examples R Language Examples

The R mean() function is used to calculate the average of a sample; the second parameter of this function can be set to remove some outlier data.

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

mean(x, trim = 0, na.rm = FALSE, ...)

Parameter Description:

Example

Create a vector

x

<-

c

(

12

,

27

,

3

,

4.2

,

2

,

2

,

54

,

21

,

4

,

2

)

Compute an average

result.

mean

<-

mean

(

x

)

print

(

result.

mean

)

The output of the code above is:

[1] 8.52

Next we use the trim parameter to remove some outliers. In the following example we set trim = 0.3, which removes from the beginning and end of the vector 20*0.3=6 data items, the ones on the left (1, 2, 3) and **(18, 19, 20)** on the right will be removed.

Example

Create a vector

x

<-

c

(

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

,

10

,

11

,

12

,

13

,

14

,

15

,

16

,

17

,

18

,

19

,

20

)

Compute an average

result.

mean

<-

 

mean

(

x,trim

=

0.3

)

result.

mean2

<-

mean

(

c

(

4

,

5

,

6

,

7

,

8

,

9

,

10

,

11

,

12

,

13

,

14

,

15

,

16

,

17

)

)

print

(

result.

mean

)

print

(

result.

mean2

)

In the above example, mean(x, trim = 0.3) removes 3 elements from each end, which is equivalent to mean(c(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)).

The output of the code above is:

[1] 10.5

[1] 10.5

In the input vector of the mean function, if an element has no value, it defaults to NA. We can use the third parameter to set whether to remove the default NA values; if NA is not removed, the returned result is NA:

Example

Create a vector

x

<-

c

(

1

,

2

,

3

,

4.5

,

6

,NA

)

Compute an average

result.

mean

<-

 

mean

(

x

)

print

(

result.

mean

)

Remove NA

result.

mean

<-

 

mean

(

x,na.

rm

=

TRUE

)

print

(

result.

mean

)

The output of the code above is:

[1] NA

[1] 3.3

R Language Examples R Language Examples