Variable name restrictions in R

梦想与她 提交于 2019-12-17 05:03:43

问题


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)


回答1:


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.




回答2:


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




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/9195718/variable-name-restrictions-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!