# How to subset dataframe whose first column is smaller than the second column?

**URL:** <https://discourse.julialang.org/t/how-to-subset-dataframe-whose-first-column-is-smaller-than-the-second-column/91178>\
**Category:** General Usage\
**Tags:** question\
**Created:** [December 3, 2022, 1:26pm UTC](https://discourse.julialang.org/t/how-to-subset-dataframe-whose-first-column-is-smaller-than-the-second-column/91178 "2022-12-03T13:26:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![zhangchunyong](https://avatars.discourse-cdn.com/v4/letter/z/d9b06d/32.png) [@zhangchunyong](https://discourse.julialang.org/u/zhangchunyong)\
**Post date:** [December 3, 2022, 1:26pm UTC](https://discourse.julialang.org/t/how-to-subset-dataframe-whose-first-column-is-smaller-than-the-second-column/91178/1 "2022-12-03T13:26:40Z")

</div>

I have a dataframe,and I want to subset the dataframe whose first column is smaller than second column.

```julia
julia> a=DataFrame(p=[1,2,3,4,5,6],q=[1,2,4,5,2,9])
6×2 DataFrame
 Row │ p q
     │ Int64 Int64
─────┼──────────────
   1 │ 1 1
   2 │ 2 2
   3 │ 3 4
   4 │ 4 5
   5 │ 5 2
   6 │ 6 9

```

I tried like the following

```julia
julia> index=a[!,:p].<a[!,:q]
julia> b=hcat(a,index)
6×3 DataFrame
 Row │ p q x1
     │ Int64 Int64 Bool
─────┼─────────────────────
   1 │ 1 1 false
   2 │ 2 2 false
   3 │ 3 4 true
   4 │ 4 5 true
   5 │ 5 2 false
   6 │ 6 9 true
julia> subset(b,:x1)
3×3 DataFrame
 Row │ p q x1
     │ Int64 Int64 Bool
─────┼────────────────────
   1 │ 3 4 true
   2 │ 4 5 true
   3 │ 6 9 true
julia> select(subset(b,:x1),:p,:q)
3×2 DataFrame
 Row │ p q
     │ Int64 Int64
─────┼──────────────
   1 │ 3 4
   2 │ 4 5
   3 │ 6 9

```

Are their any faster or easier ways?

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://discourse.julialang.org/u/jules)\
**Post date:** [December 3, 2022, 1:30pm UTC](https://discourse.julialang.org/t/how-to-subset-dataframe-whose-first-column-is-smaller-than-the-second-column/91178/2 "2022-12-03T13:30:26Z")

</div>

```julia
# DataFrames.jl only
using DataFrames
subset(a, [:p, :q] => ByRow(<))

# With DataFrameMacros.jl convenience package
using DataFrameMacros
@subset(a, :p < :q)

```

In this case you can do `ByRow(<)` so the macro solution is not much shorter, but generally for more complex things you’ll have to define an anonymous function for the normal DataFrames syntax, which is when the macro version will be quite a bit shorter.
