Creating subset using or statement

Viewed 70

I have a data frame with 6 columns and thousands of rows containing share transactions. I want to identify rows with bad price data. The following function gives me a subset with the rows with good price data:

function in_price_range(df)
    price_good = subset(df, :UnitPrice => X-> (trough_share_price .<= X .<= peak_share_price), skipmissing=true)
    return price_good
end

For a subset for bad data I tried:

function out_price_range(df)
    price_discrepancy = subset(df, :UnitPrice => X-> (X .< trough_share_price || X .> peak_share_price), skipmissing=true)
    return price_discrepancy
end

However, that givers error TypeError: non-boolean (BitVector) used in boolean context

I tried .|| rather than || but that then gives error: syntax: "|" is not a unary operator

How do I fix the code?

1 Answers

In Julia, || is

help?> ||
search: ||

  x || y

  Short-circuiting boolean OR.

The short-circuiting part meaning, that if x is true, || will not even bother to evaluate y. In other words, this will make a branch in the code. For example:

julia> 5 < 7 || print("This is unreachable")
true

This is great if you want to write code that is efficient for a case like

if something_easy_to_evaluate || something_costly_to_evaluate
    # Do something
end

In other words, this is control flow! Obviously, this cannot be broadcasted. For that, what you want is the regular or operator |, which you can broadcast with .|. So for example:

julia> a = rand(3) .< 0.5
3-element BitVector:
 1
 0
 0

julia> b = rand(3) .< 0.5
3-element BitVector:
 0
 1
 0

julia> a .|| b
ERROR: syntax: "|" is not a unary operator
Stacktrace:
 [1] top-level scope
   @ none:1

julia> a .| b
3-element BitVector:
 1
 1
 0

The same applies to && vs &; the former is only used for control-flow, the latter is normal bitwise and.

Related