how to conditionally create new column in dataframe based on other column values in julia

Viewed 389

I have a julia dataframe that looks like this:

time    data
0        34
1        34
2        30
3        37
4        32
5        35

How do I create a new binary column that is 0 if time is less than 2 and greater than 4, and 1 if not either condition?

Like this:

time    data    x
0        34     0
1        34     0
2        30     1
3        37     1
4        32     1
5        35     0

In python, I would do something like:

def func(df):
    if df.time < 2 or df.time > 4:
        return 0
    else:
        return 1
df['x'] = df.apply(func, axis=1)
1 Answers

In Julia we have the beautiful Dot Syntax which can be gracefully applied here:

julia> df[!, :x] = 2 .<= df[!, :time] .<= 4     
6-element BitVector:
0
0
1
1
1
0  

or alternatively

df.x = 2 .<= df.time .<= 4
Related