Codorado
Codorado

Reputation: 23

Julia: Convert from Vector{Any} to Vector{Symbol}

I just started coding in Julia due to the open source code of a paper that I want to use.

One remaining error appears within a

rename!(data_df, vcat([Symbol("Zbar$i") for i in 1:3],
            [Symbol("ZbarX$i") for i in []],
            [Symbol("X$i") for i in [1]], [:y,:y_pred]))

command, in which the following error occurs:

ERROR: MethodError: no method matching rename!(::DataFrame, ::Vector{Any})
Closest candidates are:
  rename!(::AbstractDataFrame) at C:\Users\###\.julia\packages\DataFrames\Lrd7K\src\abstractdataframe\abstractdataframe.jl:248
  rename!(::AbstractDataFrame, ::AbstractVector{Symbol}; makeunique) at C:\Users\###\.julia\packages\DataFrames\Lrd7K\src\abstractdataframe\abstractdataframe.jl:199
  rename!(::AbstractDataFrame, ::AbstractVector{<:AbstractString}; makeunique) at C:\Users\###\.julia\packages\DataFrames\Lrd7K\src\abstractdataframe\abstractdataframe.jl:207

.

I fixed the error by manually inserting the output of the previously shown vcat() command:

rename!(data_df_test,[:Zbar1,:Zbar2, :Zbar3, :X1, :y, :y_pred] ).

When comparing the datatype of the initial and manually inserted rename-vectors, I observe 2 different vector types: Vector{Any} (fails) and Vector{Symbol} (works).

#1

vcat([Symbol("Zbar$i") for i in 1:3],
                   [Symbol("ZbarX$i") for i in []],
                   [Symbol("X$i") for i in [1]], [:y,:y_pred])
6-element Vector{Any}:
 :Zbar1
 :Zbar2
 :Zbar3
 :X1
 :y
 :y_pred

#2

[:Zbar1,:Zbar2, :Zbar3, :X1, :y, :y_pred]
6-element Vector{Symbol}:
 :Zbar1
 :Zbar2
 :Zbar3
 :X1
 :y
 :y_pred

My question: How can I change the vcat() vector from a Vector{Any} to a Vector{Symbol}?

Upvotes: 2

Views: 211

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69879

As it was commented under your question in this case on Julia 1.8 there is no issue. However, there would be issue in the following case:

julia> vcat([Symbol("Zbar$i") for i in 1:3], [])
3-element Vector{Any}:
 :Zbar1
 :Zbar2
 :Zbar3

which is resolved by changing the syntax to:

julia> Symbol[[Symbol("Zbar$i") for i in 1:3];
              []]
3-element Vector{Symbol}:
 :Zbar1
 :Zbar2
 :Zbar3

The point is that vcat does not allow passing type-hint for target collection while by using the vector-style syntax it is possible.

The reason why we cannot reproduce the problem in your case is that under Julia 1.8:

julia> [Symbol("ZbarX$i") for i in []]
Symbol[]

(note that the same behavior is under Julia 1.0.5 so if there is a problem it must be under a very old Julia)

Upvotes: 2

Related Questions