R - 平均值、中位數和眾數



R 中的統計分析是透過使用許多內建函式來執行的。大多數這些函式都是 R 基礎包的一部分。這些函式將 R 向量作為輸入以及引數,並給出結果。

本章中我們將討論的函式是平均值、中位數和眾數。

平均值

它是透過將所有值加起來併除以資料系列中的值的數量來計算的。

函式mean()用於在 R 中計算此值。

語法

在 R 中計算平均值的語法如下:

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

以下是使用的引數的描述:

  • x 是輸入向量。

  • trim 用於從排序向量的兩端刪除一些觀測值。

  • na.rm 用於從輸入向量中刪除缺失值。

示例

# Create a vector. 
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find Mean.
result.mean <- mean(x)
print(result.mean)

當我們執行上述程式碼時,它會產生以下結果:

[1] 8.22

應用 Trim 選項

當提供 trim 引數時,向量中的值將被排序,然後從計算平均值中刪除所需數量的觀測值。

當 trim = 0.3 時,將從每個端刪除 3 個值以查詢平均值。

在這種情況下,排序後的向量為(-21,-5,2,3,4.2,7,8,12,18,54),並且從向量中刪除用於計算平均值的值是從左側刪除(-21,-5,2),從右側刪除(12,18,54)。

# Create a vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find Mean.
result.mean <-  mean(x,trim = 0.3)
print(result.mean)

當我們執行上述程式碼時,它會產生以下結果:

[1] 5.55

應用 NA 選項

如果存在缺失值,則 mean 函式將返回 NA。

要從計算中刪除缺失值,請使用 na.rm = TRUE,這意味著刪除 NA 值。

# Create a vector. 
x <- c(12,7,3,4.2,18,2,54,-21,8,-5,NA)

# Find mean.
result.mean <-  mean(x)
print(result.mean)

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

當我們執行上述程式碼時,它會產生以下結果:

[1] NA
[1] 8.22

中位數

資料系列中最中間的值稱為中位數。median()函式用於在 R 中計算此值。

語法

在 R 中計算中位數的基本語法如下:

median(x, na.rm = FALSE)

以下是使用的引數的描述:

  • x 是輸入向量。

  • na.rm 用於從輸入向量中刪除缺失值。

示例

# Create the vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find the median.
median.result <- median(x)
print(median.result)

當我們執行上述程式碼時,它會產生以下結果:

[1] 5.6

眾數

眾數是在一組資料中出現次數最多的值。與平均值和中位數不同,眾數可以同時具有數值和字元資料。

R 沒有用於計算眾數的標準內建函式。因此,我們建立一個使用者函式來計算 R 中資料集的眾數。此函式將向量作為輸入,並將眾數值作為輸出。

示例

# Create the function.
getmode <- function(v) {
   uniqv <- unique(v)
   uniqv[which.max(tabulate(match(v, uniqv)))]
}

# Create the vector with numbers.
v <- c(2,1,2,3,1,2,3,4,1,5,5,3,2,3)

# Calculate the mode using the user function.
result <- getmode(v)
print(result)

# Create the vector with characters.
charv <- c("o","it","the","it","it")

# Calculate the mode using the user function.
result <- getmode(charv)
print(result)

當我們執行上述程式碼時,它會產生以下結果:

[1] 2
[1] "it"
廣告

© . All rights reserved.