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);
Solution 1:
You have several options
integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)
Solution 2:
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:
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:
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.