Reputation: 10626
I have a vector x with nothing in it.
dput(x)
""
When I do, length(x)
or nrow(data.frame(x))
, it comes out as 1.
How would I set up a if statement where if it is empty, go to the next?
I have it as:
if(length(x)>1){
does not seem to be working.
Upvotes: 1
Views: 460
Reputation: 13046
Your vector is not empty, it consist of 1 empty string (a string of zero length).
x <- ""
dput(x)
## ""
Here, you want to test if nchar(x) == 0
or all(nchar(x) == 0)
. Alternatively, you may wish to check if nzchar(x)
returns FALSE
.
Upvotes: 5
Reputation: 8267
Your x
is not "empty". It's a vector of length 1, and the single entry is the empty character string. This is different from NULL
or NA
or many other ways of defining "emptiness" in R. (Rather Zen.)
The answer will depend on what else could conceivably be in x
. @gagolews already gave a nice answer. Alternatives could include all(x=="")
or similar. Regardless of what you do, think about whether x
could contain NULL
, or NA
with or without bona fide strings mixed in.
I think you would find The R Inferno most enlightening.
Upvotes: 0