我有一个数据框,其中每列都是类型因子并且有超过 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 ...
Run Code Online (Sandbox Code Playgroud)
更换应如下:
A=1,B=2,C=3,D=4,E=5,F=6。
如果有 3000 个级别:
“美国”=1,“英国”=2....,法国=“3000”。
该解决方案应自动检测级别(例如:3000),然后替换从 1 到 3000 的每个级别。
小智 7
例如InsectSprays,您可以使用:
levels(InsectSprays$spray) <- 1:6
Run Code Online (Sandbox Code Playgroud)
应该概括到你的问题。
因子变量已经具有与每个因子水平相对应的基础数值。您可以看到如下:
as.numeric(InsectSprays$spray)
Run Code Online (Sandbox Code Playgroud)
或者
x = factor(c("A","D","B","G"))
as.numeric(x)
Run Code Online (Sandbox Code Playgroud)
例如,如果要添加与每个级别相对应的特定数值,您可以合并查找表中的这些值:
# 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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16195 次 |
| 最近记录: |