R語言學習筆記:因子


R語言中的因子就是factor,用來表示分類變量(categorical variables),這類變量不能用來計算而只能用來分類或者計數。

可以排序的因子稱為有序因子(ordered factor)。

 

factor()

用來生成因子數據對象,語法是:

factor(data, levels, labels, ...)

其中data是數據,levels是因子的級別向量,labels是因子的標簽向量。

 

以我的10個月的fitbit數據為例,創建一個因子

fitbit <- read.csv("fitbit.csv")

fitbit$date <- as.Date(fitbit$date)

month <- factor(format(fitbit$date,"%m"))  #建立因子

這樣就按月份建立一個因子,以后就可以按月份進行分類統計了。

str(month) #看看因子的結構信息,可以看到有10個級別Levels,代表着10個月份。

Factor w/ 10 levels "01","02","03",..: 1 1 1 1 1 1 1 1 1 1 ...

length(month)  #向量的長度並不是10,而是fitbit中的數據行數。

[1] 304

summary(month)  #可以看看匯總信息,這里列出每個分類中的數據個數

01 02 03 04 05 06 07 08 09 10

31 28 31 30 31 30 31 31 30 31

ordered()

也可以建立有序的因子:

ordered_month <- ordered(format(fitbit$date,"%m"))

str(ordered_month)

Ord.factor w/ 10 levels "01"<"02"<"03"<..: 1 1 1 1 1 1 1 1 1 1 ...

可以看出各個級別有順序大小關系。

 

tapply()

統計每個月的步數

tapply(fitbit$step, month, mean)

       01        02        03        04        05        06        07        08        09        10

11263.032 10200.250 12710.065  6389.233  7228.774 10755.800 11425.903 11147.129 11210.767  9706.097

畫出圖來看看,4、5月份有缺失數據,所以平均數偏低

plot(tapply(fitbit$step, month, mean), type="b")

image

score1 <- ordered(score, levels = c('C', 'B', 'A')); score1

3、用cut()函數將一般的數據轉換成因子或有序因子。

例1:exam <- c(98, 97, 52, 88, 85, 75, 97, 92, 77, 74, 70, 63, 97, 71, 98,

65, 79, 74, 58, 59, 60, 63, 87, 82, 95, 75, 79, 96, 50, 88)

exam1 <- cut(exam, breaks = 3) #切分成3組

exam2 <- cut(exam, breaks = c(0, 59, 69, 79, 89, 100)) #切分成自己設置的組

attr(exam1, 'levels'); attr(exam2, 'levels'); attr(exam2, 'class')

ordered(exam2, labels = c('bad', 'ok', 'average', 'good', 'excellent')) #一個有序因子


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM