PatriceG
PatriceG

Reputation: 4063

How to declare a vector of zeros in R

I suppose this is trivial, but I can't find how to declare a vector of zeros in R.

For example, in Matlab, I would write:

X = zeros(1,3);

Upvotes: 89

Views: 280202

Answers (5)

Torregu
Torregu

Reputation: 11

Here are four ways to create a one-dimensional vector with zeros - then check if they are identical:

numeric(2) -> a; double(2) -> b; vector("double", 2) -> c; vector("numeric", 2) -> d
identical(a, b, c, d)

In the iteration chapter in R for Data Science they use the "d" option to create this type of vector.

Upvotes: 1

Rquest
Rquest

Reputation: 146

X <- c(1:3)*0

Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c() function, which is very frequently cited in tutorials as a usual way to declare a vector.

As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.

Upvotes: 5

989
989

Reputation: 12937

replicate is another option:

replicate(10, 0)
# [1] 0 0 0 0 0 0 0 0 0 0

replicate(5, 1)
# [1] 1 1 1 1 1

To create a matrix:

replicate( 5, numeric(3) )

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    0    0
#[2,]    0    0    0    0    0
#[3,]    0    0    0    0    0

Upvotes: 15

cdutra
cdutra

Reputation: 587

You can also use the matrix command, to create a matrix with n lines and m columns, filled with zeros.

matrix(0, n, m)

Upvotes: 27

Thierry
Thierry

Reputation: 18487

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

Upvotes: 116

Related Questions