Julia 在 R 中等效的命名向量是什么?

Nic*_*ick 5 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
Run Code Online (Sandbox Code Playgroud)

在 中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
Run Code Online (Sandbox Code Playgroud)

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

julia> xdict[[2,4]]
ERROR: KeyError: [2,4] not found in getindex at dict.jl:718
Run Code Online (Sandbox Code Playgroud)

中有类似命名数组的东西吗Julia?如果没有,那么 Julia 处理此类问题的方法是什么?

Dan*_*etz 5

尝试使用以下命令复制 R 代码NamedArrays

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
Run Code Online (Sandbox Code Playgroud)

索引技术并非最佳。欢迎大家在评论中提出改进。还可以NamedArrays轻松增强以获得更好的索引(这在 R 中会更困难)。