This question already has an answer here:
How to convert integer into categorical data in R?

(1个答案)


1年前关闭。




说我有以下df
x<-c(1,3,2,4,1,3,2,4,1,3,2,4)
y<-c(rnorm(12))
df<-data.frame(x,y)

x是整数,我尝试使用R Cookbook的建议将其转换为因子:
df[,'x']<-factor(df[,'x'])

但是它仍然是一个整数。我尝试了在论坛上找到的解决方案
df[,'x']<-lapply(df[,'x'], factor)

但它也不起作用。谢谢。

最佳答案

看来您的原始解决方案有效。检查typeof()class():

x<-c(1,3,2,4,1,3,2,4,1,3,2,4)
y<-c(rnorm(12))
df<-data.frame(x,y)
typeof(df$x)
#"double"
class(df$x)
#"numeric"
df[,'x']<-factor(df[,'x'])
typeof(df$x)
 #"integer"
class(df$x)
#"factor"

10-06 04:23
查看更多