How to include a column with a constant value in a DataFrames select

I have the following working example:

using DataFrames

# Create a DataFrame
data = DataFrame(Name=["Alice", "Bob", "Cathy", "David"],
                 Age=[30, 25, 27, 28],
                 City=["New York", "San Francisco", "Chicago", "Los Angeles"])

# Define a constant value
constant = 42

# Use the select function to include the constant value in each row of the DataFrame
new_data = select(data, :, :Name => ByRow(x -> constant) => :Constant)

Is there a better way of including a constant in this case, without resorting to passing a column, just for it to be ignored?

In 1.8 and above there is a Returns struct which just returns whatever you tell it to, no matter what arguments you call it with

julia> select(df, [] => Returns(1) => :y)
2 Likes

The updated example using @pdeffebach solution is:

using DataFrames

# Create a DataFrame
data = DataFrame(Name=["Alice", "Bob", "Cathy", "David"],
                 Age=[30, 25, 27, 28],
                 City=["New York", "San Francisco", "Chicago", "Los Angeles"])

# Define a constant value
constant_value = 42

# Use the select function to include the constant value in each row of the DataFrame
new_data = select(data, :, [] => Returns(constant_value) => :Constant)

In DataFramesMeta.jl you can also just do

@transform df :Constant = 1