簡體   English   中英

R:因素標簽如何映射到data.frame中的正確值?

[英]R: How are factor labels mapped to the correct values in a data.frame?

編輯:包括我閱讀的文檔,我仍然不清楚

我是R的新手,正在玩RStudio預加載的mtcars data.frame 我將cyl變量轉換為因子並標記它們。 我的代碼是:

df <- mtcars
str(df)
df$cyl <- factor(df$cyl, labels = c('Four cylinder', 'Six Cylinder', 'Eight Cylinder'))
str(df)

哪個輸出:

> df <- mtcars
> str(df)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
> df$cyl <- factor(df$cyl, labels = c('Four cylinder', 'Six Cylinder', 'Eight Cylinder'))
> str(df)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : Factor w/ 3 levels "Four cylinder",..: 2 2 1 2 3 2 3 1 1 2 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

我的問題是:代碼的factor部分如何正確分配標簽(即,在轉換后以1表示的'Four cylinder'在原始df正確分配了4 s)。 是否只是按升序將標簽作為默認行為應用? 如果我有一個要轉換為因子的具有10個唯一值的字段,該怎么辦。 如何確定我的標簽和替換值與正確的原始值相對應?

?factor訪問的文檔指出:

級別:x可能采用的值的可選向量(作為字符串)。 默認值是as.character(x)所采用的唯一值集,並按x的升序排序。

這似乎表明標簽應按原始變量值的升序應用,但是我只想確保我正確理解。

在此示例中知道,因為它將mtcars $ cyl中的數值轉換為字符向量c(4, 6, 8, 6, ...) -> c("4", "6", "8", ...) 4,6,8,6 c(4, 6, 8, 6, ...) -> c("4", "6", "8", ...) ,通過字母數字排序選擇級別(“ 4”,然后是“ 6”,然后是“ 8”;由於您沒有在對factor的調用中指定levels ),然后將數字值存儲在df$cyl通過將valueslevels匹配來找到。 標簽並沒有真正影響因子排序:相反,您可以將標簽“六個汽缸”與級別“ 4”匹配。

as.numeric(factor(c(4,6,8,6,6,6,4)))[1] 1 2 3 2 2 1

暫無
暫無

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

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