R mean() Function - Calculating Average Value

R 语言实例R Language Examples

The R mean() function is used to calculate the average value of samples. The second parameter of the 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:

  • xInput vector

  • trimRemove outliers from the beginning and end respectively. The value range is between 0 and 0.5, indicating the proportion of outliers to be removed before calculating the mean.

  • na.rmBoolean value, default is FALSE. Specifies whether to remove the missing value NA in the input vector. Setting TRUE removes NA.

Example

# Create vector
x <- c(12,27,3,4.2,2,2,54,-21,4,-2)

# Calculate average value
result.mean <- mean(x)
print(result.mean)

After executing the above code, the output result is:

[1] 8.52

Next, we use the trim parameter to remove some outliers. In the following example, we settrim = 0.3, then it will remove from the beginning and end of the vector20*0.3=6data items , the left(1, 2, 3)and the right (18, 19, 20)will be deleted.

Example


# Create vector
x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
# Calculate average value
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 examplemean(x,trim = 0.3)removing 3 elements from each of the beginning and end is equivalent tomean(c(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17))。

After executing the above code, the output result 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 specify whether to remove the default NA value. If NA is not removed, the returned result is NA:

Example

# Create vector
x <- c(1,2,3,4.5,6,NA)

# Calculate average value
result.mean <-  mean(x)
print(result.mean)

# Remove NA
result.mean <-  mean(x,na.rm = TRUE)
print(result.mean)

After executing the above code, the output result is:

[1] NA
[1] 3.3

R 语言实例R Language Examples

Other Extensions