Reputation: 1018
Just realize the output is different:
> y=""
> y
[1] ""
> y=character()
> y
character(0)
However, nothing odd has happened. And I am not clear about these differences, and want to keep this problem(if any) clear in mind. So, thank you for helping.
Upvotes: 7
Views: 1139
Reputation: 94202
You are confusing the length (number of elements) of a vector with the number of characters in a string:
Consider these three things:
> x=c("","")
> y=""
> z=character()
Their length is the number of elements in the vector:
> length(x)
[1] 2
> length(y)
[1] 1
> length(z)
[1] 0
To get the number of characters, use nchar
:
> nchar(x)
[1] 0 0
> nchar(y)
[1] 0
> nchar(z)
integer(0)
Note that nchar(x)
shows how many letters in each element of x
, so it returns an integer vector of two zeroes. nchar(y)
is then an integer vector of one zero.
So the last one, nchar(z)
returns an integer(0)
, which is an integer vector of no zeroes. It has length of zero. It has no elements, but if it did have elements, they would be integers.
character(0)
is an empty vector of character-type objects. Compare:
> character(0)
character(0)
> character(1)
[1] ""
> character(2)
[1] "" ""
> character(12)
[1] "" "" "" "" "" "" "" "" "" "" "" ""
Upvotes: 5
Reputation: 3174
If y=""
, then length(y)
is 1
.
On the other hand, if y=character()
, then length(y)
is 0
Upvotes: 3
Reputation: 16080
character(0)
is vector of character type with ZERO elements. But ""
is character type vector with one element, which is equal to empty string.
Upvotes: 6