问题
This is more for curiosity, but is it possible to write subscripts in R console and, if so, how would I do that?
- I am using a Mac and
- typically code in RStudio
Although assignment statements work with Greek letters, e.g. μ,σ, but I can't get superscripts or subscripts working. I'd like to write an assign statement such as σ² <- 1
and have it be recognized. In particular, typing that last command I get the following error message
Error: unexpected input in "σ�"
回答1:
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.
💻💻💻💻💻💻💻
回答2:
I am using windows so maybe this doesn't work on a mac. The following code allows superscript for me.
> assign("σ²", 3)
> σ²
[1] 3
Hope this helps :)
来源:https://stackoverflow.com/questions/35398354/using-subscripts-and-superscripts-in-r-console