2015-12-03 80 views
0

我有一个数据框,其中每列都是类型因子,并且具有超过3000个级别。 有没有一种方法可以用数值替换每个级别。 考虑内置数据帧InsectSprays用数值替换因子

> str(InsectSprays) 
'data.frame': 72 obs. of 2 variables: 
$ count: num 10 7 20 14 14 12 10 23 17 20 ... 
$ spray: Factor w/ 6 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ... 

替换应该如下:

A = 1,B = 2,C = 3,d = 4,E = 5,F = 6。

如果有3000级:

“USA”= 1, “英国”= 2 ......,法国= “3000”。

该解决方案应该自动检测水平(例如:3000),然后替换每个级别开始从1至3000。

回答

3

对于InsectSprays例如,可以使用:

levels(InsectSprays$spray) <- 1:6 

应该推广到你的问题。

1

因子变量已经具有对应于每个因子水平的基础数值。你可以看到这个如下:

as.numeric(InsectSprays$spray) 

x = factor(c("A","D","B","G")) 
as.numeric(x) 

如果你想添加对应于每个级别,你可以,例如,合并从一个查找表中的值,具体数值:

# Create a lookup table with the numeric values you want to correspond to each level of spray 
lookup = data.frame(spray=levels(InsectSprays$spray), sprayNumeric=c(5,4,1,2,3,6)) 

# Merge lookup values into your data frame 
InsectSprays = merge(InsectSprays, lookup, by="spray")