# Julia 如何改变向量的levels

``````> Sire = c("ZA","AD","BB","AD","AD","CC","CC","AD","AD")
> Sire = as.factor(Sire)
> levels(Sire)
 "AD" "BB" "CC" "ZA"
> levels(Sire) = 1:4
> Sire
 4 1 2 1 1 3 3 1 1
Levels: 1 2 3 4
``````

``````a1= ["ZA","AD","BB","AD","AD","CC","CC","AD","AD"]
``````

``````julia> Sire = ["ZA","AD","BB","AD","AD","CC","CC","AD","AD"];

julia> levels(Sire)
4-element Array{String,1}:
"BB"
"CC"
"ZA"

julia> levels(Sire) = [1,2,3,4]
ERROR: error in method definition: function Missings.levels must be explicitly imported to be extended
Stacktrace:
 top-level scope at none:0
``````

julia 这边标准库只有一些简单的数据结构，复杂的要用其他的包

``````julia> # ]add CategoricalArrays

julia> using CategoricalArrays

julia> levels(Sire)
4-element Array{String,1}:
"BB"
"CC"
"ZA"

julia> d = Dict(zip(levels(Sire), 1:4))
Dict{String,Int64} with 4 entries:
"BB" => 2
"CC" => 3
"ZA" => 4

julia> s2 = recode(Sire, d...)
9-element Array{Int64,1}:
4
1
2
1
1
3
3
1
1

julia> levels(s2)
4-element Array{Int64,1}:
1
2
3
4
``````

ref:

1 个赞

``````Sire = ["ZA","AD","BB","AD","AD","CC","CC","AD","AD"]

# methods 1
a1 = deepcopy(Sire)
new = collect(1:length(levels(Sire)))
d = Dict(zip(levels(a1),new))
using CategoricalArrays
re1 = recode(a1,d...)

# methods 2
a2 = deepcopy(Sire)
new = collect(1:length(levels(Sire)))
un = unique(a2)
replace(a2, Pair.(un, axes(un, 1))...)

# methods 3
a3 = deepcopy(Sire)
new = collect(1:length(levels(a3)))
d = Dict(zip(levels(a3),new))
re3 = replace(a3,d...)
``````

1 个赞