How to declare a vector of zeros in R

R

R Problem Overview


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);

R Solutions


Solution 1 - R

You have several options

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

Solution 2 - R

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

matrix(0, n, m)

Solution 3 - R

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

Solution 4 - R

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatriceGView Question on Stackoverflow
Solution 1 - RThierryView Answer on Stackoverflow
Solution 2 - RcdutraView Answer on Stackoverflow
Solution 3 - R989View Answer on Stackoverflow
Solution 4 - RRquestView Answer on Stackoverflow