Can I reference a range within a dataframe using named columns?

Hi,

I have a DataFrame (df) whose columns are titled col1, col2, 0, 1, 2, 3, 4 and 5.
I need to create a vector referencing the first row (1) of columns 0, 1, 2, 3, 4 and 5.

The following code works, but isn’t dynamic.

vector = Array(df[1, 3:8])

I changed the titles to yr0, yr2 etc., and changed the code to the below, but get "MethodError: no method matching -(::String, ::String)

vector = Array(df[1, "yr0":"yr1"])

Is there a way to pull in a vector/array that’s dynamic and based on the title of the column vs. index reference? I’m new to Julia and coding, but thank you for your help!

Check out ? Between.

julia> using DataFrames

julia> df = DataFrame(a = 1, b1 = 2, b2 = 3, b4 = 5);

julia> df[:, Cols(:a, Between(:b2, :b4))]
1×3 DataFrame
 Row │ a      b2     b4    
     │ Int64  Int64  Int64 
─────┼─────────────────────
   1 │     1      3      5

Here are some ways:

julia> df = DataFrame(rand(1:5, 3, 8), ["col1", "col2", string.(0:5)...])
3×8 DataFrame
 Row │ col1   col2   0      1      2      3      4      5     
     │ Int64  Int64  Int64  Int64  Int64  Int64  Int64  Int64 
─────┼────────────────────────────────────────────────────────
   1 │     1      2      3      4      1      5      3      2
   2 │     5      1      2      5      3      4      1      4
   3 │     3      4      1      4      2      4      1      1

# Brute force
df[1, ["0", "1", "2", "3", "4", "5"]]

# Same but generating the strings dynamically
df[1, string.(0:5)]

# Using a regular expression matching "0", ..., "5"
df[1, r"^[0-5]$"]

# Specifying the first and last column to extract
df[1, Between("0", "5")]
1 Like

Thank you very much!

Cheers, that’s super helpful!