rjulia

Is there a names() equivalent in Julia?


I am transferring a script written in R to Julia, and one of the R functions is the names() function. Is there a synonymous function in Julia?


Solution

  • DataFrames

    In Julia there is names function for a DataFrame which returns column names, e.g.:

    julia> using DataFrames
    
    julia> x = DataFrame(rand(3,4))
    3×4 DataFrames.DataFrame
    │ Row │ x1        │ x2       │ x3       │ x4       │
    ├─────┼───────────┼──────────┼──────────┼──────────┤
    │ 1   │ 0.721198  │ 0.605882 │ 0.191941 │ 0.597295 │
    │ 2   │ 0.0537836 │ 0.619698 │ 0.764937 │ 0.273197 │
    │ 3   │ 0.679952  │ 0.899523 │ 0.206124 │ 0.928319 │
    
    julia> names(x)
    4-element Array{Symbol,1}:
     :x1
     :x2
     :x3
     :x4
    

    Then in order to set column names of a DataFrame you can use names! function (example continued):

    julia> names!(x, [:a,:b,:c,:d])
    3×4 DataFrames.DataFrame
    │ Row │ a         │ b        │ c        │ d        │
    ├─────┼───────────┼──────────┼──────────┼──────────┤
    │ 1   │ 0.721198  │ 0.605882 │ 0.191941 │ 0.597295 │
    │ 2   │ 0.0537836 │ 0.619698 │ 0.764937 │ 0.273197 │
    │ 3   │ 0.679952  │ 0.899523 │ 0.206124 │ 0.928319 │
    

    Arrays

    Standard arrays do not support naming their dimensions. But you can use NamedArrays.jl package which adds this functionality. You can get and set names of dimensions as well as names of indices along each dimension. You can find the details here https://github.com/davidavdav/NamedArrays.jl#general-functions.