2015-02-12 11 views
6

Se scrivoIn che modo R gestisce Unicode/UTF-8?

`Δ` <- function(a,b) (a-b)/a 

allora posso includere U+394 fintanto che è racchiusa in apici inversi. (Al contrario, Δ <- function(a,b) (a-b)/a fallisce con unexpected input in "�".) Quindi apparentemente R analizza UTF-8 o Unicode o qualcosa del genere. L'incarico si svolge bene e lo stesso vale per la valutazione di

`Δ`(1:5, 9:13) 

. E posso anche valutare Δ(1:5, 9:13).

Infine, se ho definito qualcosa di simile winsorise <- function(x, λ=.05) { ... } poi λ (U+3bb) non bisogno di essere "introdotto per" R con un apice inverso. Posso quindi chiamare winsorise(data, .1) senza problemi.


L'unica mention nella documentazione di R posso trovare di Unicode è sopra la mia testa. Potrebbe qualcuno che lo capisca meglio spiegarmi - cosa sta succedendo "sotto il cofano" quando R ha bisogno del ` per capire l'assegnazione a ♔, ma può analizzare ♔ (a, b, c) una volta assegnato?

+0

nel settore della R-internals: Cosa Gli utenti R pensano che le variabili o gli oggetti siano simboli associati a un valore. Penso che la sezione CHARSXP a cui sei collegato sia il valore, e tu sei realmente interessato alle regole per i simboli. Detto questo, ho lavorato su codice R scritto in cinese, quindi mi aspetterei che il delta funzioni. –

+1

Quale versione di R stai usando/quale OS/quale locale? Ottengo "Errore: \ uXXXX sequenze non supportate all'interno apici inversi (linea 1)" quando si assegna una funzione a 'Δ' (testato su R-devel di oggi e 3.1.0 sotto Win 7, inglese UK locale.) –

+0

Quale versione di R stai usando la funzione 'Δ <- (a, b) (ab)/a' fallisce? E quando lo dici "fallisce", cosa intendi? Hai un errore di sintassi? Se ha funzionato per me su 'R versione 3.1.0, x86_64-apple-darwin10.8.0 (64-bit)' locale en_US.UTF-8 – MrFlick

risposta

1

Per la cronaca, sotto R-devel (2015/02/11 r67792), Win 7, locale inglese UK, vedo:

options(encoding = "UTF-8") 

`Δ` <- function(a,b) (a-b)/a 
## Error: \uxxxx sequences not supported inside backticks (line 1) 

Δ <- function(a,b) (a-b)/a 
## Error: unexpected input in "\" 

"Δ" <- function(a,b) (a-b)/a  # OK 

`Δ`(1:5, 9:13) 
## Error: \uxxxx sequences not supported inside backticks (line 1) 

Δ(1:5, 9:13) 
## Error: unexpected input in "\" 

"Δ"(1:5, 9:13) 
## Error: could not find function "Δ" 
+0

OK interessante. Non mi sarei mai aspettato che ciò differisse tra le varie versioni. – isomorphismes

4

Non posso parlare di quello che sta succedendo sotto il cofano sulla funzione chiama vs argomenti della funzione, ma this email from Prof. Ripley partire dal 2008 può far luce (estratto sotto):

R passes around, prints and plots UTF-8 character data pretty well, but it translates to the native encoding for almost all character-level manipulations (and not just on Windows). ?Encoding spells out the exceptions [...]

la ragione R non questa traduzione (in Windows almeno) è menzionato in the documentation that the OP linked to:

Windows has no UTF-8 locales, but rather expects to work with UCS-2 strings. R (being written in standard C) would not work internally with UCS-2 without extensive changes.

La documentazione R per ?Quotes spiega come a volte è possibile utilizzare i caratteri out-of-locale in ogni caso (enfasi aggiunta):

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.

C'è un altro modo per arrivare a tali caratteri, che sta utilizzando l'unicode sequenza di escape (come \u0394 per Δ). Questa è di solito una pessima idea se stai usando quel carattere per qualcosa di diverso dal testo su un grafico (cioè, non farlo per i nomi di variabili o funzioni, vedi questa citazione da the R 2.7 release notes, quando gran parte dell'attuale UTF-8 il supporto è stato aggiunto):

If a string presented to the parser contains a \uxxxx escape invalid in the current locale, the string is recorded in UTF-8 with the encoding declared. This is likely to throw an error if it is used later in the session, but it can be printed, and used for e.g. plotting on the windows() device. So "\u03b2" gives a Greek small beta and "\u2642" a 'male sign'. Such strings will be printed as e.g. <U+2642> except in the Rgui console (see below).

Penso che questo rivolge la maggior parte delle vostre domande, anche se non so il motivo per cui v'è una differenza tra il nome della funzione e la funzione degli argomenti esempi hai dato; si spera che qualcuno più esperto possa sentirlo. Cordiali saluti, su Linux tutti questi modi diversi di assegnazione e chiamare un lavoro funzione senza errori (perché la lingua del sistema è UTF-8, quindi è necessario che si verificano senza traduzione):

Δ <- function(a,b) (a-b)/a   # no error 
`Δ` <- function(a,b) (a-b)/a  # no error 
"Δ" <- function(a,b) (a-b)/a  # no error 
"\u0394" <- function(a,b) (a-b)/a # no error 
Δ(1:5, 9:13)  # -8.00 -4.00 -2.67 -2.00 -1.60 
`Δ`(1:5, 9:13)  # same 
"Δ"(1:5, 9:13)  # same 
"\u0394"(1:5, 9:13) # same 

sessionInfo() 

# R version 3.1.2 (2014-10-31) 
# Platform: x86_64-pc-linux-gnu (64-bit) 

# locale: 
# LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C    LC_TIME=en_US.UTF-8 
# LC_COLLATE=en_US.UTF-8 LC_MONETARY=en_US.UTF-8  LC_MESSAGES=en_US.UTF-8 
# LC_PAPER=en_US.UTF-8 LC_NAME=C     LC_ADDRESS=C 
# LC_TELEPHONE=C   LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C 

# attached base packages: 
# stats graphics grDevices utils datasets methods base 
+0

Grazie per aver fatto tutta questa ricerca. Non avevo idea che ci fosse una differenza così significativa tra Windows e Linux fino a UTF-8, ma questo spiega le persone che hanno commentato i fallimenti. (E sono contento di sapere che è meno probabile a 32 bit che a Windows che causa i loro errori.) – isomorphismes

+0

grazie a @isomorphismes. L'ho appena modificato leggermente per renderlo più coerente, ma le stesse informazioni di base sono lì. In breve: qualsiasi stranezza legata all'unicode è quasi sempre colpa di Windows, ma non ha nulla a che fare con 32 vs 64 bit. Si tratta di UTF-8 rispetto a UCS-2 (FYI, se stai leggendo ulteriormente, UCS-2 è anche conosciuto come "UTF-16LE con BOM"). – drammock

+0

@isomorphismes Sotto R 3.1.2 (Win 7 64 bit) 'get (" Δ ") (1,2)' verrà eseguito senza errori – mnel

Problemi correlati