R variable names: characters / names or something else?

After reading the official R documentation, as well as some of the tutorials provided, you will learn that variable names are treated as language objects - that is, they are characters of aka names.

On p. 14 of the R language definition guide (version 3.1.1) under the heading Symbol LookUp is a simple example: "y <- 4 ... y is a symbol and 4 is its value" . What is confusing is that is.symbol(y) or equivalent to is.name(y) , return FALSE (for the quoted and unquoted argument y). When someone forces a variable to a character with y <- as.name(4) , then is.symbol(y) and is.name(y) return TRUE . Thus, it seems that variable names are not characters / names until they are forced to do so. What object R is the name of the variable before it is forced into the character?

Thanks for helping me resolve this confusion.

+7
variables r
source share
1 answer

It is important to understand what is.symbol and is.name . Firstly, it is really the same function. notice, that

 is.symbol # function (x) .Primitive("is.symbol") is.name # function (x) .Primitive("is.symbol") 

so the characters / names are really the same thing in R. So here I just use is.name

But also note that these functions check if the "subject" is that the name you pass in points is a symbol or name. They are looking for what the name indicates.

So if you did

 # rm(foo) make sure it doesn't exist is.name(foo) # Error: object 'foo' not found 

You will get an error message. Despite the fact that foo is the name itself, what it points to is not yet defined. He is trying to "find" the meaning of foo . notice, that

 quote(foo) # foo is.name(quote(foo)) # [1] TRUE 

So, quote will treat the parameter as a language object, and you can check it this way. Now, if we define foo to specify a name

 (foo <- as.name("hello")) # hello is.name(foo) # [1] TRUE 

but if we point to something else

 (foo <- "hello") # [1] "hello" is.name(foo) # [1] FALSE is.character(foo) # [1] TRUE 

then it no longer points to a name (here it points to a symbol)

Thus, variable names are names / characters, but usually most of the functions of R will work with what they point to, and not return information about the name itself. So the problem was that you misinterpreted the work of is.name and is.symbol . It really really matters when you program in a language.

+11
source share

All Articles