Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable name restrictions in R

Tags:

r

r-faq

What are the restrictions as to what characters (and maybe other restrictions) can be used for a variable name in R?

(This screams of general reference, but I can't seem to find the answer)

like image 452
Kyle Brandt Avatar asked Feb 08 '12 14:02

Kyle Brandt


People also ask

What are the naming restrictions for a variable?

A variable name must start with a letter or an underscore character (_) A variable name cannot start with a digit. A variable name can only contain alpha-numeric characters and underscores ( a-z, A-Z , 0-9 , and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables)

Which of the following Cannot be used as the name of a variable in R?

Reserved words or keywords are not allowed to be defined as a variable name. Special characters such as '#', '&', etc., along with White space (tabs, space) are not allowed in a variable name.

How long can variable names be in R?

name , "Names are limited to 10,000 bytes (and were to 256 bytes in versions of R before 2.13.

What is Cannot be used as a variable name?

Reserved keywords cannot be used as variable names. Reserved keywords are ALL, AND, BY, EQ, GE, GT, LE, LT, NE, NOT, OR, TO, and WITH. Variable names can be defined with any mixture of uppercase and lowercase characters, and case is preserved for display purposes.


2 Answers

You might be looking for the discussion from ?make.names:

A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number. Names such as ".2way" are not valid, and neither are the reserved words.

In the help file itself, there's a link to a list of reserved words, which are:

if else repeat while function for in next break

TRUE FALSE NULL Inf NaN NA NA_integer_ NA_real_ NA_complex_ NA_character_

Many other good notes from the comments include the point by James to the R FAQ addressing this issue and Josh's pointer to a related SO question dealing with checking for syntactically valid names.

like image 92
joran Avatar answered Oct 09 '22 22:10

joran


Almost NONE! You can use 'assign' to make ridiculous variable names:

assign("1",99) ls() # [1] "1" 

Yes, that's a variable called '1'. Digit 1. Luckily it doesn't change the value of integer 1, and you have to work slightly harder to get its value:

1 # [1] 1 get("1") # [1] 99 

The "syntactic restrictions" some people might mention are purely imposed by the parser. Fundamentally, there's very little you can't call an R object. You just can't do it via the '<-' assignment operator. "get" will set you free :)

like image 45
Spacedman Avatar answered Oct 09 '22 22:10

Spacedman