user1744318
user1744318

Reputation: 99

What R function will return the number of characters contained in this variable?

In R I have a variable, h10.

> h10
[1] "<meta name=\"Distribution\" content=\"Global\" />"

> class(h10)
[1] "character"


> str(h10)
chr "<meta name=\"Distribution\" content=\"Global\" />"

I want to know the number of characters in h10, but length() returns 1 and not 45.

> length(h10)
[1] 1

What will return the number of characters? What am I doing wrong?

Upvotes: 2

Views: 219

Answers (1)

agstudy
agstudy

Reputation: 121568

You should use nchar (as commented) :

nchar(h10)
[1] 45

You can still use length after splitting you string to character's vector:

length(unlist(strsplit(h10,'')))
[1] 45

edit(thanks to @MatthewPlourde comment ) :

length returns 1 is because h10 is not a string, it's a string vector of length 1. It's important to know that in R, there are no "scalar" data types, only vectors. When you assign a string to a variable, as in h10 <- '<meta name...>', you're telling R to create a character vector of length 1 and assign this value to the first position

Upvotes: 3

Related Questions