In this tutorial, we will look at how to create a vector of ones (having 1 as its elements) in R with the help of some examples.

## How to create a vector of ones in R?

You can create a vector of ones in R using different methods. For example, using the `c()`

function, using the `rep()`

function, etc. Let’s look at these methods with the help of examples.

### Using `c()`

function

The `c()`

is used to create a vector by combining different values (and/or vectors) together. You can use the `c()`

function to create a vector of ones if the length of the vector is relatively small.

For example, let’s create a vector of ones of length four.

# create a vector of ones vec <- c(1, 1, 1, 1) # display the vector print(vec)

Output:

[1] 1 1 1 1

We get a vector of four ones.

Manually typing `1`

can become cumbersome if you want to create a large vector of ones. Thus, it’s recommended to use the `rep()`

function.

## Using `rep()`

function

You can use the `rep()`

function in R to create a vector with a value repeated a specified number of times. The following is the syntax –

rep(x, t)

It creates a vector with the value x repeated t times.

To create a vector of ones, pass 1 as the first argument to the `rep()`

function and the length of the vector as its second argument.

Let’s look at an example. We’ll create the same vector as above – a vector of four ones.

# create a vector of ones vec <- rep(1, 4) # display the vector print(vec)

Output:

[1] 1 1 1 1

We get a vector of four ones. The same result we got above.

You might also be interested in –

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**