我想改变向量的级数,但我不知道如何在julia中做到这一点。
我的julia版本是1.1,我的代码是:
Sire = ["ZA","AD","BB","AD","AD","CC","CC","AD","AD"]
levels(Sire)
levels(Sire) = [1,2,3,4]错误消息:
julia> levels(Sire) = [1,2,3,4]
ERROR: error in method definition: function Missings.levels must be explicitly imported to be extended
Stacktrace:
[1] top-level scope at none:0发布于 2019-08-12 17:53:08
你可能想使用CategoricalArrays.jl包来处理分类数据(如果你需要更多关于它的信息,请发表评论,我可以给你更多信息)。
如果你使用标准的Vector,你可以像这样使用replace函数:
julia> Sire = ["ZA","AD","BB","AD","AD","CC","CC","AD","AD"]
9-element Array{String,1}:
"ZA"
"AD"
"BB"
"AD"
"AD"
"CC"
"CC"
"AD"
"AD"
julia> l = unique(Sire)
4-element Array{String,1}:
"ZA"
"AD"
"BB"
"CC"
julia> replace(Sire, Pair.(l, axes(l, 1))...)
9-element Array{Any,1}:
1
2
3
2
2
4
4
2
2或者,您可以手动完成最后一步:
julia> replace(Sire, "ZA"=>1, "AD"=>2, "BB"=>3, "CC"=>4)
9-element Array{Any,1}:
1
2
3
2
2
4
4
2
2请注意,unique按照值的出现顺序返回值。如果你想要一个特定的订单,你应该相应地改变l (例如sort! it)。
发布于 2019-08-13 10:00:39
我做一个总结:
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...)https://stackoverflow.com/questions/57457123
复制相似问题