Variable name restrictions in R

前端 未结 4 1153
慢半拍i
慢半拍i 2020-11-29 06:01

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

相关标签:
4条回答
  • 2020-11-29 06:40

    The following may not directly address your question but is of great help. Try the exists() command to see if something already exists and this way you know you should not use the system names for your variables or function. Example...

       > exists('for')
       [1] TRUE
    
       >exists('myvariable')
       [1] FALSE
    
    0 讨论(0)
  • 2020-11-29 06:47

    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.

    0 讨论(0)
  • 2020-11-29 06:52

    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 :)

    0 讨论(0)
  • 2020-11-29 07:00

    Using the make.names() function from the built in base package may help:

    is_valid_name<- function(x)
    {
      length_condition = if(getRversion() < "2.13.0") 256L else 10000L
      is_short_enough = nchar(x) <= length_condition
      is_valid_name = (make.names(x) == x)
    
      final_condition = is_short_enough && is_valid_name
      return(final_condition)
    }
    
    0 讨论(0)
提交回复
热议问题