You can, but you shouldn't; names that don't stick to R's standards cause problems eventually.
The rules, from ?Quotes
:
Names and Identifiers
Identifiers consist of a sequence of letters, digits, the period (.)
and the underscore. They must not start with a digit nor underscore,
nor with a period followed by a digit. Reserved words are not valid
identifiers.
The definition of a letter depends on the current locale, but only
ASCII digits are considered to be digits.
Such identifiers are also known as syntactic names and may be used
directly in R code. Almost always, other names can be used provided
they are quoted. The preferred quote is the backtick (`), and deparse
will normally use it, but under many circumstances single or double
quotes can be used (as a character constant will often be converted to
a name). One place where backticks may be essential is to delimit
variable names in formulae: see formula.
If you still want to break the rules, there are a couple ways. You can use assign
:
> assign('σ²', 47)
> `σ²`
[1] 47
> σ²
Error: unexpected input in "σ�"
Notice, however, that dependent on your locale, you may need to wrap σ²
in backticks to call it successfully.
You can also wrap it in backticks to assign:
> `σ²` <- 47
> `σ²`
[1] 47
> σ²
Error: unexpected input in "σ�"
As you can see, you'll still likely need to wrap any calls in backticks (especially if you want your code to be faintly portable).
That said, this is all a REALLY, REALLY BAD IDEA.
- Your variable names will be hard to type;
- Your code will likely not be portable;
- You stand a very good chance of causing errors in more complicated functions later (e.g. NSE functions would be very unpredictable);
- It's a good way to do really stupid things:
like
> `+` <- `-`
> 1 + 1
[1] 0
The rules are there for a reason. Unless you've got a really good reason to break them, don't.
Addendum
If you just want to use symbolic expressions as strings, encodeString
and format
are both useful:
> encodeString('σ²')
[1] "σ²"
> format('σ²')
[1] "σ²"
See their help pages for more specifics, but it's generally possible to use any symbol (even emoji!) in a string, if you're a little careful what functions you pass it to.