1. 程式人生 > >R語言學習筆記 —— table 函式的應用

R語言學習筆記 —— table 函式的應用

一、table 函式對應的就是統計學中的列聯表,是一種記錄頻數的方法,對於統計來說有非常重要的應用,下面的例子都是針對維數為2的情況舉例,多維的情況是類似的

下面看一個例子:

> ct <- data.frame(
+         Vote.for.X = factor(c("Yes", "Yes", "No", "Not Sure", "No"), levels = c("Yes", "No", "Not Sure")),
+         Vote.for.X.Last.Time =  factor(c("Yes", "No", "No", "Yes", "No"), levels = c("Yes", "No"))
+       )
> ct
  Vote.for.X Vote.for.X.Last.Time
1        Yes                  Yes
2        Yes                   No
3         No                   No
4   Not Sure                  Yes
5         No                   No
> cttab <-table(ct)
> cttab
          Vote.for.X.Last.Time
Vote.for.X Yes No
  Yes        1  1
  No         0  2
  Not Sure   1  0

首先我們建立了一個示例資料集合,其中我們指定我們的因子的水平,然後 table 函式則是統計所有因子對出現的情況的頻數

下面看一下 cttab 的特點:

> mode(cttab)
[1] "numeric"
> str(cttab)
 'table' int [1:3, 1:2] 1 0 1 1 2 0
 - attr(*, "dimnames")=List of 2
  ..$ Vote.for.X          : chr [1:3] "Yes" "No" "Not Sure"
  ..$ Vote.for.X.Last.Time: chr [1:2] "Yes" "No"
> summary(cttab)
Number of cases in table: 5 
Number of factors: 2 
Test for independence of all factors:
	Chisq = 2.9167, df = 2, p-value = 0.2326
	Chi-squared approximation may be incorrect
> attributes(cttab)
$dim
[1] 3 2

$dimnames
$dimnames$Vote.for.X
[1] "Yes"      "No"       "Not Sure"

$dimnames$Vote.for.X.Last.Time
[1] "Yes" "No" 


$class
[1] "table"


二、table物件的操作

一個必須要掌握的操作,addmargins

> addmargins(cttab)
          Vote.for.X.Last.Time
Vote.for.X Yes No Sum
  Yes        1  1   2
  No         0  2   2
  Not Sure   1  0   1
  Sum        2  3   5

下面取出各維度的名字,也就是各個的水平
> dimnames(cttab)
$Vote.for.X
[1] "Yes"      "No"       "Not Sure"

$Vote.for.X.Last.Time
[1] "Yes" "No" 

下面提取感興趣的子表:subtable 類比 subset

subtable(tbl,subnames) tbl 感興趣的表,subnames 一個類表,列出自己各個維度感興趣的水平, subtable 實現如下

subtable <- function(tbl, subnames) {
  #將 table 轉換稱 array 獲得 table 裡面的所有元素
  tblarray <- unclass(tbl)
  
  #將 tblarray 以及 subnames 組合到一個list中
  dcargs <- list(tblarray)
  ndims <- length(subnames)
  for(i in 1:ndims) {
    dcargs[[i+1]] <- subnames[[i]]
  }
  
  #等價與執行 dcargs[[1]][dcargs[[2]][i], dcargs[[3]][j]] i,j 取遍所有該屬性的元素
  subarray <- do.call("[", dcargs)
 
  #對list中的每一個屬性呼叫 length
  dims <- lapply(subnames, length)
  subtbl <- array(subarray, dims, dimnames = subnames)
  class(subtbl) <- "table"
  return(subtbl)
} 

下面給出一個例子:可能很有用的
> as.data.frame(cttab)
  Vote.for.X Vote.for.X.Last.Time Freq
1        Yes                  Yes    1
2         No                  Yes    0
3   Not Sure                  Yes    1
4        Yes                   No    1
5         No                   No    2
6   Not Sure                   No    0

tabdom 計算table的統計頻率

tabdom <- function(tbl, k) {
  tbldf <- as.data.frame(tbl)
  freqord <- order(tabldf$Freq, decreasing=TRUE)
  dom <- tbldf[freqord, ][1:k]
  return(dom)
}


注意:aggregate() 函式  cut() 函式