Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R variable names: symbols/names or something else?

Tags:

variables

r

Reading through the official R documentation as well as some of the contributed tutorials one learns that variable names are regarded as language objects - i.e. they are symbols aka names.

On p. 14 of the R Language Definition manual (version 3.1.1) under the heading of Symbol LookUp is a simple example: "y <- 4 ... y is a symbol and 4 is its value". What is confusing about this is that is.symbol(y), or equivalently is.name(y), return FALSE (for quoted and unquoted argument y). When one coerces the variable into a symbol with y <- as.name(4), then is.symbol(y) and is.name(y) return TRUE. So it seems that variable names are not symbols/names until they are coerced into such. What kind of R object is a variable name before it is coerced into a symbol?

Thanks for your help in clearing up this confusion.

like image 267
nt54 Avatar asked Aug 11 '14 02:08

nt54


1 Answers

It's important to understand what is.symbol and is.name are doing. First, they are really the same function. Observe that

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

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

But also note that these functions are checking if the "thing" that the name you pass in points to is a symbol or a name. They are looking up what the name points to.

So if you did

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

you get an error. Despite the fact that foo is a name itself, what it points to is not yet defined. It's trying to "look-up" the value of foo. Observe that

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

So quote will treat the parameter like a language object and you can test it that way. Now if we define foo to point to a name

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

but if we point it to something else

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

then it is no longer pointing to a name (here, it points to a character)

So variable names are names/symbols, but generally most R function will work with what they point to rather than return information about the name itself. So the problem was you were misinterpreting how is.name and is.symbol were working. It only really makes a difference when you are programming on the language.

like image 118
MrFlick Avatar answered Nov 15 '22 16:11

MrFlick