I am looking for a more elegant way to do this
data[(data.ID .== 1) .| (data.ID .== 4) .| (data.ID .== 7) .| (data.ID .== 10),: ]
where data is a DataFrame. I simply want to extract rows where the ID value is one of the four specified. I was trying stuff like data.ID .== [1,4,7,10]. But this breaks because of the broadcasting.
One way to do it is by using Ref
julia> df = DataFrame(:ID => collect(1:10), :x => 'a':'j')
julia> df[in.(df.ID, Ref((1, 4, 7, 10))), :]
4Γ2 DataFrame
β Row β ID β x β
β β Int64 β Char β
βββββββΌββββββββΌβββββββ€
β 1 β 1 β 'a' β
β 2 β 4 β 'd' β
β 3 β 7 β 'g' β
β 4 β 10 β 'j' β
It is easy with filter:
filter(row β row.ID in [1,4,7,10], data)
I suggest also to to read the DataFrame Tutorial , it is very informative about DataFrames.
julia> data = DataFrame(:ID=>[1, 4, 7, 10, 20])
5Γ1 DataFrame
β Row β ID β
β β Int64 β
βββββββΌββββββββ€
β 1 β 1 β
β 2 β 4 β
β 3 β 7 β
β 4 β 10 β
β 5 β 20 β
julia> filter(row->row.ID in [1,4,7], data)
3Γ1 DataFrame
β Row β ID β
β β Int64 β
βββββββΌββββββββ€
β 1 β 1 β
β 2 β 4 β
β 3 β 7 β
Okay thank you both, Iβll check out the tutorial
nilshg
March 12, 2020, 4:36pm
5
Skoffer:
df[in.(df.ID, Ref((1, 4, 7, 10))), :]
I also like the Fix2 version of in which I find more readable:
df[in([1, 4, 7, 10]).(df.ID), :]
Since nobody else has mentioned it, you might also find DataFramesMeta to be useful.