Differences between character() and “” in R

风流意气都作罢 提交于 2019-12-08 17:37:19

问题


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.


回答1:


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] "" "" "" "" "" "" "" "" "" "" "" ""



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/23040895/differences-between-character-and-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!