R ones: How to Create a Vector of Ones in R

By Dr. Zubair Khalid, DVM, MS, PhD ·

R ones: How to Create a Vector of Ones in R

Creating an R ones vector is one of the first small skills that pays off in modeling work. You use rep(1, n) to build a vector of ones of any length, and matrix(1, nrow, ncol) to fill a matrix with ones. This article shows the syntax, a worked example, common errors, and where an r ones vector actually helps in data analysis.

Quick Answer

  • rep(1, 5) returns [1, 1, 1, 1, 1], a numeric vector of length 5.
  • matrix(1, nrow = 3, ncol = 2) returns a 3x2 matrix where every cell is 1.
  • length(rep(1, 5)) is 5, and sum(rep(1, 5)) is 5.
  • Use rep(1L, n) if you need an integer vector instead of a double vector.
  • A column of ones is the standard intercept column in linear algebra and regression design matrices.

Syntax

The two functions you need are rep() and matrix(). Both are base R, so no package is required.

rep(x, times) repeats the value x a given number of times.

ArgumentRequired?Meaning
xYesThe value to repeat. Use 1 for a vector of ones.
timesYes for this taskHow many times to repeat x. This sets the vector length.
eachNoRepeats each element of x before moving on. Not needed for a single value.
length.outNoAn alternative to times that forces an exact output length.

matrix(data, nrow, ncol) builds a matrix and recycles data to fill it.

ArgumentRequired?Meaning
dataYesThe value to fill with. Use 1 for a matrix of ones.
nrowUsuallyNumber of rows.
ncolUsuallyNumber of columns.
byrowNoDefaults to FALSE, so filling happens column by column.

How It Works

R recycles a single value across the requested length. When you call rep(1, 5), R takes the scalar 1 and repeats it five times, producing a double-precision numeric vector. The same recycling rule drives matrix(). If you pass a single 1 and ask for 3 rows and 2 columns, R fills all 6 cells with that value.

The fill order matters for matrices. With the default byrow = FALSE, R fills down the first column, then the second column, and so on. For a matrix of identical ones the order is invisible, but the habit matters once you fill with real data.

A vector of ones has two useful properties. Its length tells you how many observations it covers, and its sum equals that length. That second property is why a ones column works as an intercept: multiplying it by a coefficient adds a constant to every row of a model.

If you want an integer vector instead of a double, write rep(1L, 5). The L suffix tells R to store the value as an integer. For most statistical work the double version is fine, and it avoids type coercion surprises when you combine it with other numeric vectors.

Worked Example

The context is a small lab measurement table with five samples. You want a ones vector that matches the number of rows, and a small matrix of ones to see the fill behavior.

sample_idreading
S112.4
S215.1
S39.8
S414.2
S511.6

The table has 5 rows, so a matching ones vector needs length 5.

v <- rep(1, 5)
m <- matrix(1, nrow = 3, ncol = 2)
v
m

Output:

[1] 1 1 1 1 1
     [,1] [,2]
[1,]    1    1
[2,]    1    1
[3,]    1    1

Step by step:

  1. rep(1, 5) produces [1, 1, 1, 1, 1]. This matches the 5 rows of the lab table.
  2. length(rep(1, 5)) is 5, confirming the vector length equals the row count.
  3. sum(rep(1, 5)) is 5, which equals $X^\top X$ for an intercept-only design on 5 observations.
  4. matrix(1, nrow = 3, ncol = 2) produces a 3x2 matrix of ones.
  5. The matrix has nrow ncol = 3 2 = 6 total elements, all equal to 1.

The vector and the matrix use the same recycling rule. Only the shape differs.

More Examples

Match a data frame's row count. If your data has n rows, build the intercept column with the same length.

n <- nrow(df)
ones <- rep(1, n)

Build a design matrix column. Combine a ones column with a predictor to form a two-column design matrix.

x <- c(2, 4, 6, 8)
X <- cbind(rep(1, length(x)), x)
X

Create a constant matrix. Multiplying a matrix of ones by a scalar gives a constant matrix, which is handy for testing matrix code.

matrix(1, nrow = 2, ncol = 3) * 5

Use length.out for an exact size. This is useful when the length comes from a computed value.

rep(1, length.out = 4)

Build an integer vector. Use the L suffix when downstream code expects integers.

rep(1L, 3)

If you are still getting comfortable with vector construction, the guide on c() in R for creating vectors covers the building blocks that pair well with rep(). When you need conditional values inside a vector, ifelse in R shows the vectorized approach. And if you later plot results and want to mark a reference line at 1, the R lines() function explains how to add lines to an existing plot.

Errors and How to Fix Them

rep(1, -3) raises an error. A negative times gives Error: invalid 'times' argument. Check that your length variable is zero or positive before calling rep().

matrix(1, nrow = 3) with no ncol. R infers one column, giving a 3x1 matrix. If you expected a wider matrix, pass both dimensions.

rep(1, c(2, 3)) raises an error. When times is a vector, it must have the same length as x, so a length-2 times with a single 1 gives invalid 'times' argument. Pass a single number when you want one block.

Non-numeric input. rep("1", 5) creates a character vector, not a numeric one. Arithmetic on it fails or coerces in ways you may not expect. Drop the quotes.

Dimension mismatch in cbind(). If your ones vector length does not match the other columns, cbind() recycles or errors. Always set the length from nrow() of the data.

Confusing rep() with replicate(). replicate() repeats an expression and returns a matrix or list. For a plain vector of ones, rep() is the right tool.

Common Mistakes

  • Using rep(1, n) where n is a column count instead of a row count. The fix is to derive the length from nrow(data), not ncol(data).
  • Forgetting that matrix() fills column-wise by default. The fix is to remember the fill order, or set byrow = TRUE when the order matters.
  • Assuming rep(1, 5) is an integer vector. It is a double vector. The fix is to use rep(1L, 5) when integer storage is required.
  • Building a ones vector once and reusing it after the data changes. The fix is to rebuild it from the current row count each time.
  • Writing rep(1, 5, 2) and expecting length 5. The third positional argument is length.out, so you get length 2. The fix is to name the argument: rep(1, times = 5).
  • Treating a ones column as a real predictor. The fix is to recognize it as the intercept term and let the modeling function handle it.

Limitations

A vector of ones carries no information beyond its length. It cannot encode group membership, weights, or any measured quantity. If you need a column that varies, you need real data or a transformation of it.

Memory is another constraint. A length-10-million ones vector still occupies storage proportional to its length, even though every value is identical. For very large problems, sparse representations or implicit intercept handling in modeling functions avoid materializing the full vector.

There is also a modeling caveat. Adding a ones column to a design matrix that already contains an intercept creates perfect collinearity, and the model fit will drop one of the terms or fail. Most formula interfaces add the intercept automatically, so you rarely need to build the ones column by hand.

Frequently Asked Questions

How do I create a vector of ones in R?

Use rep(1, n), where n is the number of elements you want. For example, rep(1, 5) returns [1, 1, 1, 1, 1]. This is base R and needs no packages.

How do I create a matrix of ones in R?

Use matrix(1, nrow = r, ncol = c). R recycles the single value 1 across all r * c cells. For a 3x2 matrix, matrix(1, nrow = 3, ncol = 2) gives six ones.

What is the difference between rep(1, 5) and rep(1L, 5)?

rep(1, 5) returns a double-precision numeric vector. rep(1L, 5) returns an integer vector. Both hold the value 1 five times, but the storage type differs, which can matter when you combine vectors or pass them to functions that check types.

Why does my ones vector have the wrong length?

The most common cause is passing a length that does not match your data. Derive the length from nrow(data) so the vector always matches the current row count. Also check that you did not pass a vector to times, which changes the output length.

Do I need a ones column for regression in R?

Usually no. Formula interfaces like lm(y ~ x) add an intercept automatically. A manual ones column is useful when you build design matrices yourself, for example with cbind() or matrix algebra, and you want explicit control over the intercept term.

References

This article draws on the standard references listed under Further Reading.

Further Reading

Related Articles