您好,登錄后才能下訂單哦!
這篇“R語言如何創建因子”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“R語言如何創建因子”文章吧。
在R語言當中有因子這個特殊的數據結構,和別的編程語言不同,這個數據結構的主要目的是用來分類,計算頻數和頻率,在后期將R語言用于統計學當中將會十分受用。并且在繪圖當中,我們使用同樣的數據,將其轉化為因子之后,在將這些數據放入繪制圖像的函數當中,圖像將會變得更加具有可讀性。
使用factor()函數通過將向量作為輸入創建因子。
# Create a vector as input. data <- c("East","West","East","North","North","East","West","West","West","East","North") print(data) print(is.factor(data)) # Apply the factor function. factor_data <- factor(data) print(factor_data) print(is.factor(factor_data))
當我們執行上面的代碼,它產生以下結果 :
[1] "East" "West" "East" "North" "North" "East" "West" "West" "West" "East" "North" [1] FALSE [1] East West East North North East West West West East North Levels: East North West [1] TRUE
其次,在創建具有文本數據列的任何數據框時,R語言將文本列視為分類數據并在其上創建因子。
# Create the vectors for data frame. height <- c(132,151,162,139,166,147,122) weight <- c(48,49,66,53,67,52,40) gender <- c("male","male","female","female","male","female","male") # Create the data frame. input_data <- data.frame(height,weight,gender) print(input_data) # Test if the gender column is a factor. print(is.factor(input_data$gender)) # Print the gender column so see the levels. print(input_data$gender)
當我們執行上面的代碼,它產生以下結果:
height weight gender 1 132 48 male 2 151 49 male 3 162 66 female 4 139 53 female 5 166 67 male 6 147 52 female 7 122 40 male [1] TRUE [1] male male female female male female male Levels: female male
可以通過使用新的等級次序再次應用因子函數來改變因子中的等級的順序。
data <- c("East","West","East","North","North","East","West","West","West","East","North") # Create the factors factor_data <- factor(data) print(factor_data) # Apply the factor function with required order of the level. new_order_data <- factor(factor_data,levels = c("East","West","North")) print(new_order_data)
當我們執行上面的代碼,它產生以下結果:
[1] East West East North North East West West West East North Levels: East North West [1] East West East North North East West West West East North Levels: East West North
我們可以使用gl()函數生成因子級別。它需要兩個整數作為輸入,指示每個級別有多少級別和多少次。
gl(n, k, labels)
以下是所使用的參數的說明 -
n是給出級數的整數。
k是給出復制數目的整數。
labels是所得因子水平的標簽向量。
v <- gl(3, 4, labels = c("Tampa", "Seattle","Boston")) print(v)
當我們執行上面的代碼,它產生以下結果:
Tampa Tampa Tampa Tampa Seattle Seattle Seattle Seattle Boston [10] Boston Boston Boston Levels: Tampa Seattle Boston
以上就是關于“R語言如何創建因子”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。