0

我有一个矩阵,所有条目都是整数。并且列中的值是离散的。因此,我想将它们存储为因子。我已将每一列转换为因子。但是条目的类型现在变成了字符。我发现转换为字符是默认设置。但后来我尝试了手册中给出的内容

M is the integer matrix

say x <- M[,1]

factor(x,levels=as.integer(x))

但这仍然给出字符条目

任何帮助,将不胜感激

谢谢

4

1 回答 1

1

使用您的示例

set.seed(123)
M <- matrix(sample(1:5,30,replace=TRUE),nrow=5)
x <- M[,1]

# now make a factor - added unique around x to prevent a warning
test <- factor(x,levels=as.integer(unique(x)))

这导致:

> test
[1] 2 4 3 5 5
Levels: 2 4 3 5

> is.factor(test)
[1] TRUE
> is.character(test)
[1] FALSE
> is.numeric(test)
[1] FALSE
> str(test)
 Factor w/ 4 levels "2","4","3","5": 1 2 3 4 4
于 2013-05-22T04:46:36.587 回答