什么是朱莉娅在R中的等效命名向量?

时间:2016-01-02 01:13:39

标签: julia

R中,我们可以为矢量中的每个项目命名:

> x = c( 2.718 , 3.14 , 1.414 , 47405 )            # define the vector
> names(x) = c( "e" , "pi" , "sqrt2" , "zipcode" ) # name the components
> x[c(2,4)]                   # which indices to include
pi zipcode
3.14 47405.00
> x[c(-1,-3)]                 # which indices to exclude
pi zipcode
3.14 47405.00
> x[c(FALSE,TRUE,FALSE,TRUE)] # for each position, include it?
pi zipcode
3.14 47405.00

Julia中,我的第一个想法是使用Dict

julia> x = [2.718, 3.14, 1.414, 47405]
4-element Array{Float64,1}:
     2.718
     3.14 
     1.414
 47405.0  

julia> namelist = ["e", "pi", "sqrt2", "zipcode"]
4-element Array{ASCIIString,1}:
 "e"      
 "pi"     
 "sqrt2"  
 "zipcode"

julia> xdict=Dict(zip(namelist, x))
Dict{ASCIIString,Float64} with 4 entries:
  "e"       => 2.718
  "zipcode" => 47405.0
  "pi"      => 3.14
  "sqrt2"   => 1.414

julia> xdict["pi"]
3.14

但是,Dict丢失了原始数组的顺序,这意味着我无法访问R中的项目:

julia> xdict[[2,4]]
ERROR: KeyError: [2,4] not found in getindex at dict.jl:718

Julia中是否有类似命名的数组?如果没有,朱莉娅的方式是什么来处理这类问题?

2 个答案:

答案 0 :(得分:3)

尝试使用NamedArrays复制R代码:

julia> using NamedArrays

julia> xx = NamedArray([2.718, 3.14, 1.414, 47405],
                       (["e", "pi", "sqrt2", "zipcode"],))
4-element NamedArrays.NamedArray...
e       2.718  
pi      3.14   
sqrt2   1.414  
zipcode 47405.0

julia> xx[[2,4]]
2-element NamedArrays.NamedArray...
pi      3.14   
zipcode 47405.0

julia> xx[setdiff(1:end,[1,3])]
2-element NamedArrays.NamedArray...
pi      3.14   
zipcode 47405.0

julia> xx[[1:end...][[false,true,false,true]]]
2-element NamedArrays.NamedArray...
pi      3.14   
zipcode 47405.0

索引技术不是最佳的。 欢迎在评论中进行改进。也可以轻松地增强NamedArrays以便更好地建立索引(这在R中会更难)。

答案 1 :(得分:1)

对于遇到此问题的任何人——Julia 有命名元组,它是等效的数据结构,可以像这样创建:

(e=2.718, pi=3.14159, sqrt2 = 1.44, zipcode=47405)