Reputation: 4497
I was about to ask another question on SO that this question popped up in my mind. How we define an object with a weird name. For instance, suppose we would like to call an object "test^#". If I wanted to define it, I would use " ":
"test^#" <- 10
Now the question is how to call this object? If we again use " ", then R considers it as a character string and not the name of an object. While I see practical applications in being able to use symbols in the object names, but at this point it's more a question out of my curiosity.
Thanks,
Upvotes: 2
Views: 328
Reputation: 179388
Use backticks:
"test^#" <- 10
ls()
[1] "test^#"
Now use it:
`test^#`
[1] 10
You can also use backticks to refer to columns in data frames (or lists) with non-standard names. For example:
iris$`Sepal length` <- iris$Sepal.Length
str(iris)
'data.frame': 150 obs. of 6 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Sepal length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
summary(iris$`Sepal length`)
Min. 1st Qu. Median Mean 3rd Qu. Max.
4.300 5.100 5.800 5.843 6.400 7.900
If you want to something really odd, like embedding backticks in the name, then you may have to use get()
to refer to it:
"test^`#" <- 20
get("test^`#")
[1] 20
Upvotes: 7