簡體   English   中英

R 中的因子級別未顯示為數字

[英]factor level in R not displayed as numeric

我有一個包含 200 萬行的 data.frame。 其中一列是一個字母數字 Id,它在該列中重復,唯一計數為 300000?

>head(df$ID)
    ID 
AB00153232de 
AB00153232de    
AB00153232de 
AB00155532gh 
AB00155532gh 
AB00158932ij

>df$ID<-factor(df$ID)

當我嘗試打印該因子變量時,我得到如下信息:

>df$ID
[1] AB00153232de AB00153232de AB00153232de AB00155532gh AB00155532gh AB00158932ij 
320668 Levels: AB00153232de AB00155532gh AB00158932ij..... 

因子是否沒有存儲為數字向量,為什么?

在因子變量上使用unclass 它將因子水平保留為新變量的屬性,以便將來需要時可以使用它。

df1$ID
#     [1] AB00153232de AB00153232de AB00153232de AB00155532gh AB00155532gh AB00158932ij
# Levels: AB00153232de AB00155532gh AB00158932ij

unclass(df1$ID)
# [1] 1 1 1 2 2 3
# attr(,"levels")
# [1] "AB00153232de" "AB00155532gh" "AB00158932ij"

數據:

df1 <- structure(list(ID = structure(c(1L, 1L, 1L, 2L, 2L, 3L), 
                                     .Label = c("AB00153232de", "AB00155532gh", "AB00158932ij"), class = "factor")), 
                 .Names = "ID", row.names = c(NA, -6L), class = "data.frame")

使用as.integer(df$ID)代替。

例子:

R> ex <- as.factor(LETTERS)
R> ex
 [1] A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Levels: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
R> str(ex)
 Factor w/ 26 levels "A","B","C","D",..: 1 2 3 4 5 6 7 8 9 10 ...
R> as.integer(ex)
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
R> 

暫無
暫無

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

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