搜尋感興趣的網誌

所有文章連結

2022年3月30日 星期三

R Packages forcats - fct_inorder | R包forcats - fct_inorder

 


fct_inorde算是一個系列,包含fct_inorder、fct_infreq、fct_insrq,差別在於排序的模式不同,除了修改排序外,並沒有甚麼其他組合方式,排序方式如 : 

fct_inorder : 按照第一次出現的順序

fct_infreq : 按照出現次數

fct_insrq : 按照級別的數值


基本語法

fct_inorder(dataset$var)

fct_infreq(dataset$var)

fct_insrq(dataset$var)


建立數據框包含數字與字元

# 建立數據框
factor_df <- tibble(
    letter = c("c", "b", "a", "a", "c", "a", "b", "a", "c", "b", "b"),
    number = c(1, 2, 3, 2, 1, 1, 1, 2, 3, 1, 1)
)

# 輸出結果
r$> factor_df # A tibble: 11 x 2 letter number <chr> <dbl> 1 c 1 2 b 2 3 a 3 4 a 2 5 c 1 6 a 1 7 b 1 8 a 2 9 c 3 10 b 1 11 b 1


以fct_inorder、infreq進行排序,函數接受字符作為輸入,所以可以不轉換為因子,以下為不轉換因子直接以字符輸入

# 不轉換因子直接輸入
fct_inorder(factor_df$letter)

# 輸出結果
r$> fct_inorder(factor_df$letter) [1] c b a a c a b a c b b Levels: c b a


# 不轉換因子直接輸入
fct_infreq(factor_df$letter)

r$> fct_infreq(factor_df$letter) [1] c b a a c a b a c b b Levels: a b c


轉換為因子後輸入,結果是一樣的

# 將欄位轉換為因子
factor_df$letter <- factor(factor_df$letter)


# 轉換因子後輸入
fct_inorder(factor_df$letter)

# 輸出結果
r$> fct_inorder(factor_df$letter) [1] c b a a c a b a c b b Levels: c b a


# 轉換因子後輸入
fct_infreq(factor_df$letter)

# 輸出結果
r$> fct_infreq(factor_df$letter) [1] c b a a c a b a c b b Levels: a b c


數字欄位進行就需要轉換為因子才能進行,否則會出現ERROR

# 不轉換因子直接輸入
fct_inseq(factor_df$number)

# 輸出結果
r$> fct_inseq(factor_df$number) Error: `f` must be a factor (or character vector).


# 進行轉換
factor_df$number <- factor(factor_df$number)

# 轉換因子後輸入
fct_inseq(factor_df$number)

# 輸出結果
r$> fct_inseq(factor_df$number) [1] 1 2 3 2 1 1 1 2 3 1 1 Levels: 1 2 3

沒有留言:

張貼留言

其他文章

看看精選文章

納希克房價分析 | Nashik Apartment Price Analyze – 語法解析(上)

  這次 Nashik 的房價分析有上傳至 Kaggle ,有興趣的朋友可以前往閱覽, RMarkdown PDF 報告存放在 Google 雲端,程式碼則是存放於 Github ,照慣例會分享好用的函式語法,雖說基本的 Packages 與語法可能很多人都會完整的閱覽,但是實際...