Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between character() and "" in R

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.

like image 343
Zander Avatar asked Apr 13 '14 09:04

Zander


3 Answers

character(0) is vector of character type with ZERO elements. But "" is character type vector with one element, which is equal to empty string.

like image 167
bartektartanus Avatar answered Sep 23 '22 09:09

bartektartanus


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] "" "" "" "" "" "" "" "" "" "" "" ""
like image 43
Spacedman Avatar answered Sep 24 '22 09:09

Spacedman


If y="", then length(y) is 1. On the other hand, if y=character(), then length(y) is 0

like image 22
Randy Lai Avatar answered Sep 21 '22 09:09

Randy Lai