I wonder, how can I create a numeric zero-length vector in R?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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')
回答2:
Simply:
x <- vector(mode="numeric", length=0)
回答3:
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
回答4:
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