簡體   English   中英

將因子級別更改為R中具有不同順序的數字

[英]Change levels in factor to numbers with different order in R

我的數據集中有一個與以下因素相似的列:

response = c("Met Expectations", "Exceeded Expectations", "Exceeded    Expectations", "Unacceptable", NA, "Did not meet Expectations" )
factor(response, levels = c("Exceeded Expectations", "Met Expectations", "Did not meet Expectations", "Unacceptable"))

這就是我得到的關卡。 我已經按照在數據集中獲取的方式進行了排序。

[1] Met Expectations          Exceeded Expectations     Exceeded Expectations     Unacceptable             
[5] <NA>                      Did not meet Expectations
Levels: Exceeded Expectations Met Expectations Did not meet Expectations Unacceptable

我想將這些級別轉換為數字。 所以我嘗試了這個:

as.numeric(factor(response, levels = c("Exceeded Expectations", "Met Expectations", "Did not meet Expectations", "Unacceptable")))

我得到正確的輸出:

[1]  2  1  1  4 NA  3

但是我希望順序是4 3 2 1而不是1 2 34。我期望:

Exceeding Expectation to be 4
Met Expectations to be 3
Did not meet Expectations to be 2
Unacceptable to be 1
[1] 3  4  4  1  NA  2

如何更改訂單? 有沒有直接的方法可以做到這一點,否則我可以在將數字轉換為數字后修改數字。 在此示例中,我可以更改級別參數的順序並獲得所需的內容,但是由於我的數據集按照以下特定順序為我提供了級別:

級別:超出期望達到期望未達到期望不可接受

我正在嘗試找出一種簡單的方法。

當您創建因子時,請更改為levels = rev(c("Exceeded Expectations", "Met Expectations", "Did not meet Expectations", "Unacceptable")) rev將反轉級別的順序,從而反轉分配給類別標簽的數值的順序。

response = c("Met Expectations", "Exceeded Expectations", "Exceeded Expectations", "Unacceptable", NA, "Did not meet Expectations")

response = factor(response, levels = c("Exceeded Expectations", "Met Expectations", "Did not meet Expectations", "Unacceptable"))

as.numeric(response)

#[1]  2  1  1  4 NA  3

response = factor(response, levels = rev(c("Exceeded Expectations", "Met Expectations", "Did not meet Expectations", "Unacceptable")))

as.numeric(response)

#[1]  3  4  4  1 NA  2

如果您不想更改因子變量中水平的順序,則可以執行以下操作:

response = factor(response, levels = c("Exceeded Expectations", "Met Expectations", "Did not meet Expectations", "Unacceptable"))

# Convert to numeric with numeric order of factor reversed
5 - as.numeric(response)

#[1]  3  4  4  1 NA  2

如果級別數可以變化,您還可以動態計算級別數:

# Convert to numeric with numeric order of factor reversed
length(unique(na.omit(response))) + 1 - as.numeric(response)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM