Add a column with a constant value to a DataFrame

Solution 1:

To create such column:

df = DataFrame(x = 1:10, y = 'a':'j', d = 1)

To append such column to the existing DataFrame, you need broadcasting:

df.e .= 1

or

df[:, "f"] .= 1

Solution 2:

A more general alternative is:

julia> insertcols!(df, :z => 1)
10×3 DataFrame
 Row │ x      y     z
     │ Int64  Char  Int64
─────┼────────────────────
   1 │     1  a         1
   2 │     2  b         1
   3 │     3  c         1
   4 │     4  d         1
   5 │     5  e         1
   6 │     6  f         1
   7 │     7  g         1
   8 │     8  h         1
   9 │     9  i         1
  10 │    10  j         1

which by default does the same, but it additionally:

  1. allows you to specify the location of the new column;
  2. by default makes sure that you do not accidentally overwrite an existing column