I wonder, how can I create a numeric zero-length vector in R?
Asked
Active
Viewed 2.1e+01k times
4 Answers
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
-
1I apologize for the down vote; it was completely accidental and I only just noticed it had happened. It won't let me change. Sorry. – Stuart R. Jefferys May 11 '13 at 21:26
-
1And if the empty vector is intended to hold dates, what would you use? – Zelbinian Dec 16 '15 at 20:43
-
@Zelbinian That's a curiosity. What are you trying to achieve by doing that? – BroVic Oct 28 '17 at 12:47
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

Md. Sahidul Islam
- 563
- 2
- 9
-
1I 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
-
-
2Length 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