2017-02-09 39 views
1

我有一个200万行的data.frame。其中一列是一个字母数字标识,在该列中重复出现,其唯一计数为300000?R中的因子级别不显示为数字

>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..... 

不被存储为数字向量,为什么因素是什么?

回答

1

在因子变量使用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") 
+0

我可以用这些水平在向量或数组索引吗? – TUSHAr

+0

如果你只想在执行'unclass'之后的级别,试试这个:'attributes(unclass(df1 $ ID))$ levels' – Sathish

+0

我有一个data.frame有两个这样的因子变量,我从中创建了一个二维数组(矩阵)。我的问题是,如果我尝试访问矩阵元素M [“factor1”,“factor2”],R将通过数字级别在内部搜索它,还是通过字符值进行搜索?在第二种情况下,我可能必须编写额外的逻辑来搜索数值作为优化步骤。 – TUSHAr

0

改为使用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> 
相关问题