---
title: "Locales"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Locales}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
library(readr)
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```

The goal of readr's locales is to encapsulate common options that vary between languages and localities. This includes:

* The names of months and days, used when parsing dates.
* The default time zone, used when parsing datetimes.
* The character encoding, used when reading non-ASCII strings.
* Default date format, used when guessing column types.
* The decimal and grouping marks, used when reading numbers.

(Strictly speaking these are not locales in the usual technical sense of the word because they also contain information about time zones and encoding.)

To create a new locale, you use the `locale()` function:

```{r}
locale()
```

This rest of this vignette will explain what each of the options do.

All of the parsing function in readr take a `locale` argument. You'll most often use it with `read_csv()`, `read_fwf()` or `read_table()`. Readr is designed to work the same way across systems, so the default locale is English centric like R. If you're not in an English speaking country, this makes initial import a little harder, because you have to override the defaults. But the payoff is big: you can share your code and know that it will work on any other system. Base R takes a different philosophy. It uses system defaults, so typical data import is a little easier, but sharing code is harder.

Rather than demonstrating the use of locales with `read_csv()` and fields, in this vignette I'm going to use the `parse_*()` functions. These work with a character vector instead of a file on disk, so they're easier to use in examples. They're also useful in their own right if you need to do custom parsing. See `type_convert()` if you need to apply multiple parsers to a data frame.

## Dates and times

### Names of months and days

The first argument to `locale()` is `date_names`, and it controls what values are used for month and day names. The easiest way to specify it is with a ISO 639 language code:

```{r}
locale("ko") # Korean
locale("fr") # French
```

If you don't already know the code for your language, [Wikipedia](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) has a good list. Currently readr has `r length(date_names_langs())` languages available. You can list them all with `date_names_langs()`.

Specifying a locale allows you to parse dates in other languages:

```{r}
parse_date("1 janvier 2015", "%d %B %Y", locale = locale("fr"))
parse_date("14 oct. 1979", "%d %b %Y", locale = locale("fr"))
```

For many languages, it's common to find that diacritics have been stripped so they can be stored as ASCII. You can tell the locale that with the `asciify` option:

```{r}
parse_date("1 août 2015", "%d %B %Y", locale = locale("fr"))
parse_date("1 aout 2015", "%d %B %Y", locale = locale("fr", asciify = TRUE))
```

Note that the quality of the translations is variable, especially for the rarer languages. If you discover that they're not quite right for your data, you can create your own with `date_names()`. The following example creates a locale with Māori date names:

```{r}
maori <- locale(date_names(
  day = c("Rātapu", "Rāhina", "Rātū", "Rāapa", "Rāpare", "Rāmere", "Rāhoroi"),
  mon = c("Kohi-tātea", "Hui-tanguru", "Poutū-te-rangi", "Paenga-whāwhā",
    "Haratua", "Pipiri", "Hōngongoi", "Here-turi-kōkā", "Mahuru",
    "Whiringa-ā-nuku", "Whiringa-ā-rangi", "Hakihea")
))
```

### Timezones

Unless otherwise specified, readr assumes that times are in UTC, the Universal Coordinated Time (this is a successor to GMT and for almost all intents is identical). UTC is most suitable for data because it doesn't have daylight savings - this avoids a whole class of potential problems. If your data isn't already in UTC, you'll need to supply a `tz` in the locale:

```{r}
parse_datetime("2001-10-10 20:10")
parse_datetime("2001-10-10 20:10", locale = locale(tz = "Pacific/Auckland"))
parse_datetime("2001-10-10 20:10", locale = locale(tz = "Europe/Dublin"))
```

You can see a complete list of time zones with `OlsonNames()`.

If you're American, note that "EST" is a Canadian time zone that does not have DST. It's not Eastern Standard Time! Instead use:

* PST/PDT = "US/Pacific"
* CST/CDT = "US/Central"
* MST/MDT = "US/Mountain"
* EST/EDT = "US/Eastern"

(Note that there are more specific time zones for smaller areas that don't follow the same rules. For example, "US/Arizona", which follows mostly follows mountain time, but doesn't have daylight savings. If you're dealing with historical data, you might need an even more specific zone like "America/North_Dakota/New_Salem" - that will get you the most accurate time zones.)

Note that these are only used as defaults. If individual times have timezones and you're using "%Z" (as name, e.g. "America/Chicago") or "%z" (as offset from UTC, e.g. "+0800"), they'll override the defaults. There's currently no good way to parse times that use US abbreviations.

Note that once you have the date in R, changing the time zone just changes its printed representation - it still represents the same instants of time. If you've loaded non-UTC data, and want to display it as UTC, try this snippet of code:

```{r, eval = FALSE}
is_datetime <- sapply(df, inherits, "POSIXct")
df[is_datetime] <- lapply(df[is_datetime], function(x) {
  attr(x, "tzone") <- "UTC"
  x
})
```

### Default formats

Locales also provide default date and time formats. The date format is used when guessing column types. The default date format is `%AD`, a flexible YMD parser (see `?parse_date`):

```{r}
str(parse_guess("2010-10-10"))
str(parse_guess("2010/10/10"))
```

If you're an American, you might want to use your illogical date system::

```{r}
str(parse_guess("01/31/2013"))
str(parse_guess("01/31/2013", locale = locale(date_format = "%m/%d/%Y")))
```

The time format is also used when guessing column types. The default time format is `%AT`, a flexible HMS parser (see `?parse_time`):

```{r}
str(parse_guess("17:55:14"))
str(parse_guess("5:55:14 PM"))
# Example of a non-standard time
str(parse_guess("h5m55s14 PM"))
str(parse_guess("h5m55s14 PM", locale = locale(time_format = "h%Hm%Ms%S %p")))
```

## Character

All readr functions yield strings encoded in UTF-8. This encoding is the most likely to give good results in the widest variety of settings. By default, readr assumes that your input is also in UTF-8. This is less likely to be the case, especially when you're working with older datasets.

The following code illustrates the problems with encodings:

<!-- not currently evaluating the next two chunks due to https://github.com/tidyverse/readr/issues/1337 --!>
```{r, eval = FALSE}
library(stringi)
x <- "Émigré cause célèbre déjà vu.\n"
y <- stri_conv(x, "UTF-8", "latin1")

# These strings look like they're identical:
x
y
identical(x, y)

# But they have difference encodings:
Encoding(x)
Encoding(y)

# That means while they print the same, their raw (binary)
# representation is actually quite different:
charToRaw(x)
charToRaw(y)

# readr expects strings to be encoded as UTF-8. If they're
# not, you'll get weird characters
parse_character(x)
parse_character(y)

# If you know the encoding, supply it:
parse_character(y, locale = locale(encoding = "latin1"))
```

If you don't know what encoding the file uses, try [`guess_encoding()`](https://readr.tidyverse.org/reference/encoding.html). It's not 100% perfect (as it's fundamentally a heuristic), but should at least get you pointed in the right direction:

```{r, eval = FALSE}
guess_encoding(x)
guess_encoding(y)

# Note that the first guess produces a valid string, but isn't correct:
parse_character(y, locale = locale(encoding = "ISO-8859-2"))
# But ISO-8859-1 is another name for latin1
parse_character(y, locale = locale(encoding = "ISO-8859-1"))
```

## Numbers

Some countries use the decimal point, while others use the decimal comma. The `decimal_mark` option controls which readr uses when parsing doubles:

```{r}
parse_double("1,23", locale = locale(decimal_mark = ","))
```

Additionally, when writing out big numbers, you might have `1,000,000`, `1.000.000`, `1 000 000`, or `1'000'000`. The grouping mark is ignored by the more flexible number parser:

```{r}
parse_number("$1,234.56")
parse_number("$1.234,56", 
  locale = locale(decimal_mark = ",", grouping_mark = ".")
)

# readr is smart enough to guess that if you're using , for decimals then
# you're probably using . for grouping:
parse_number("$1.234,56", locale = locale(decimal_mark = ","))
```
