Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Column Name as an argument to Julia DataFrame?

Consider the following table:

julia> using RDatasets, DataFrames
julia> anscombe = dataset("datasets","anscombe")
11x8 DataFrame
| Row | X1 | X2 | X3 | X4 | Y1    | Y2   | Y3    | Y4   |
|-----|----|----|----|----|-------|------|-------|------|
| 1   | 10 | 10 | 10 | 8  | 8.04  | 9.14 | 7.46  | 6.58 |
| 2   | 8  | 8  | 8  | 8  | 6.95  | 8.14 | 6.77  | 5.76 |
| 3   | 13 | 13 | 13 | 8  | 7.58  | 8.74 | 12.74 | 7.71 |
| 4   | 9  | 9  | 9  | 8  | 8.81  | 8.77 | 7.11  | 8.84 |
| 5   | 11 | 11 | 11 | 8  | 8.33  | 9.26 | 7.81  | 8.47 |
| 6   | 14 | 14 | 14 | 8  | 9.96  | 8.1  | 8.84  | 7.04 |
| 7   | 6  | 6  | 6  | 8  | 7.24  | 6.13 | 6.08  | 5.25 |
| 8   | 4  | 4  | 4  | 19 | 4.26  | 3.1  | 5.39  | 12.5 |
| 9   | 12 | 12 | 12 | 8  | 10.84 | 9.13 | 8.15  | 5.56 |
| 10  | 7  | 7  | 7  | 8  | 4.82  | 7.26 | 6.42  | 7.91 |
| 11  | 5  | 5  | 5  | 8  | 5.68  | 4.74 | 5.73  | 6.89 |

Now I want to define a function f1(., ., .) that will take a data frame, a value and a field name as input, and returns the row corresponding to the matched field value.

julia> function f1(df, val, field)
          return df[df[:field] .== val, :]
       end

I'm getting the following error

julia> f1(anscombe, 11, "X1")
ERROR: KeyError: key :field not found
 in getindex at ./dict.jl:697 [inlined]
 in getindex(::DataFrames.Index, ::Symbol) at /home/username/.julia/v0.5/DataFrames/src/other/index.jl:114
 in getindex at /home/username/.julia/v0.5/DataFrames/src/dataframe/dataframe.jl:228 [inlined]
 in f1(::DataFrames.DataFrame, ::String, ::Int64) at ./REPL[229]:2

But the following is fine:

julia> anscombe[anscombe[:X1] .== 11, :]
1×8 DataFrames.DataFrame
│ Row │ X1 │ X2 │ X3 │ X4 │ Y1   │ Y2   │ Y3   │ Y4   │
├─────┼────┼────┼────┼────┼──────┼──────┼──────┼──────┤
│ 1   │ 11 │ 11 │ 11 │ 8  │ 8.33 │ 9.26 │ 7.81 │ 8.47 │

FYI I'm using Julia Version 0.5.2. How should I overcome the problem? Thanks in Advance! :)

like image 565
aroyc Avatar asked Oct 28 '25 04:10

aroyc


1 Answers

My heartfelt thanks to @Dan Getz for the solution

SOLUTION BY Dan Getz !!! Here is the correct way:

julia> function f1(df, row, field)
         return df[df[Symbol(field)] .== row, :]
       end
julia> f1(anscombe,  11, "X1")
1×8 DataFrames.DataFrame
│ Row │ X1 │ X2 │ X3 │ X4 │ Y1   │ Y2   │ Y3   │ Y4   │
├─────┼────┼────┼────┼────┼──────┼──────┼──────┼──────┤
│ 1   │ 11 │ 11 │ 11 │ 8  │ 8.33 │ 9.26 │ 7.81 │ 8.47 │
like image 147
aroyc Avatar answered Oct 30 '25 10:10

aroyc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!