How to create a numerical vector of zero length in R

I wonder how I can create a numerical vector of zero length in R?

+74
vector r numeric zero
Sep 27
source share
4 answers

If you read the help for vector (or numeric or logical or character or integer or double , "raw" or complex , etc.), you will see that they all have the argument length (or length.out , which defaults to 0

therefore

 numeric() logical() character() integer() double() raw() complex() vector('numeric') vector('character') vector('integer') vector('double') vector('raw') vector('complex') 

All return the length vectors of the corresponding atomic modes.

 # the following will also return objects with length 0 list() expression() vector('list') vector('expression') 
+88
Sep 27 '12 at 6:09
source share

Simply:

 x <- vector(mode="numeric", length=0) 
+43
Sep 27
source share

Suppose you want to create a vector x whose length is zero. Now let v be any vector.

 > v<-c(4,7,8) > v [1] 4 7 8 > x<-v[0] > length(x) [1] 0 
+3
Jun 23 '14 at 14:28
source share

This is not a very pretty answer, but this is what I use to create zero length vectors:

 0[-1] # numeric ""[-1] # character TRUE[-1] # logical 0L[-1] # integer 

A literal is a vector of length 1, and [-1] removes the first element from the vector (the only element in this case), leaving the vector with zero elements.

As a bonus, if you need one NA appropriate type:

 0[NA] # numeric ""[NA] # character TRUE[NA] # logical 0L[NA] # integer 
+1
Sep 28 '16 at 15:04
source share



All Articles