A. Hartman
A. Hartman

Reputation: 253

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?

Upvotes: 5

Views: 1657

Answers (2)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69839

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.

Upvotes: 6

James Cook
James Cook

Reputation: 160

I'm not an R expert but I think you want fieldnames

type Foo
    bar::Int
end
@show fieldnames(Foo)
baz = Foo(2)
@show fieldnames(baz)

Upvotes: 1

Related Questions