94

I wonder, how can I create a numeric zero-length vector in R?

BroVic
  • 979
  • 9
  • 26
Surjya Narayana Padhi
  • 7,741
  • 25
  • 81
  • 130

4 Answers4

112

If you read the help for vector (or numeric or logical or character or integer or double, 'raw' or complex etc ) then you will see that they all have a length (or length.out argument 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 0 length vectors of the appropriate atomic modes.

# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')
mnel
  • 113,303
  • 27
  • 265
  • 254
57

Simply:

x <- vector(mode="numeric", length=0)
srctaha
  • 1,394
  • 1
  • 14
  • 16
4

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
  • 1
    I don't know what is happening there. Again my answer is mark down. Why??? I want to know explanation. Can anyone give me answer why my answer marks down? – Md. Sahidul Islam Mar 18 '15 at 12:10
  • You are taking the length of vector element. – upInCloud Sep 13 '15 at 10:17
  • 2
    Length is the proven that, the numeric vector (here x) has zero length vector. And x vector is created from any other vector. So x is the desired vector of zero length. Also you should check the heading of the problem clearly? @ShaaradDalvi – Md. Sahidul Islam Sep 14 '15 at 09:13
3

This isn't a very beautiful answer, but it's 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 (the only element in this case) from the vector, leaving a vector with zero elements.

As a bonus, if you want a single NA of the respective type:

0[NA]     # numeric
""[NA]    # character
TRUE[NA]  # logical
0L[NA]    # integer
Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88