# Updated PLZ – Cantons Tools for R

Thanks to Eva Van Belle pointing out issues with Appenzell postcodes, I’m happy to announce an update to the postcode to cantons conversion script for R. It’s essentially a database with Swiss postcodes (PLZ) and what canton they are in. For 16 postcodes only a probabilistic assignment is possible, and this is handled by siding with the (typically much) larger municipality.

Convert Swiss postcodes to cantons: https://gist.github.com/druedin/6690720

Two simple helper functions to go with: https://gist.github.com/druedin/8758265

# Custom Tables of Descriptive Statistics in R

Here’s how we can quite easily and flexibly create tables of descriptive statistics in R. Of course, we can simply use `summary(variable_name)`, but this is not what you’d include in a manuscript — so not what you want when compiling a document in knitr/Rmarkdown.

First, we identify the variables we want to summarize. Often our database includes many more variables:

vars <- c("variable_1", "variable_2", "variable_3")

Note that these are the variable names in quotes. Second, we use `lapply()` to calculate whatever summary statistic we want. This is where flexibility kicks in: have you ever tried to include an interpolated median in such a table, just as easy as the mean in R. Here’s an example with the mean, minimum, maximum, and median:

`v_mean <- lapply(dataset[vars], mean, na.rm=TRUE)`
`v_min <- lapply(dataset[vars], min, na.rm=TRUE)`
`v_max <- lapply(dataset[vars], max, na.rm=TRUE)`
`v_med <- lapply(dataset[vars], median, na.rm=TRUE)`

Too many digits? We can use `round()` to get rid of them. There’s actually an argument ‘digits’ in the `kable()` command we’ll use in a minute that in principle allows rounding at the very end, but unfortunately it often fails on me. Rounding:

`v_mean <- round(as.numeric(v_mean), 2)`

Now we only need to bring the different summary statistics together:

`v_tab <- cbind(mean=v_mean, min=v_min, max=v_max, median=v_med)`

`rownames(v_tab) <- c("Variable 1", "A description of variable 2", "Variable 3")`

and we use `kable()` to generate a decent table:

`kable(v_tab)`

If this looks complicated, bear in mind that with no additional work you can change the order of the variables and include any summary statistics. That’s table A1 in the appendix sorted.

# Set Encoding When Importing CSV Data in R Under Windows

This is another simple thing I keep on looking up: how to set the encoding when importing CSV data in R under Windows. I need this when my data file is in UTF-8 (pretty standard these days), but I’m using R under Windows; or when I have a Windows-encoded file when using R elsewhere. The default encoding in Windows is not UTF-8, and R uses the default encoding — well, by default. Typically this is not an issue unless my data file contains accented characters in strings, which can lead to garbled text when the wrong encoding is set/assumed.

The solution is quite simple: add `encoding=""` to the `read.csv()` command, like this:

`x <- read.csv("datafile.csv", encoding="Windows-1252")`

or like this:

`x <- read.csv("datafile.csv", encoding="UTF-8")`

# How to run a regression on a subset in R

Sometimes we need to run a regression analysis on a subset or sub-sample. That’s quite simple to do in R. All we need is the `subset` command. Let’s look at a linear regression:

`lm(y ~ x + z, data=myData)`

Rather than run the regression on all of the data, let’s do it for only women, or only people with a certain characteristic:

`lm(y ~ x + z, data=subset(myData, sex=="female"))`

`lm(y ~ x + z, data=subset(myData, age > 30))`

The `subset()` command identifies the data set, and a condition how to identify the subset.

# How to Calculate the Mode in R

This is something I keep looking up, because for whatever reason R does not come with a built-in function to calculate the mode. (The `mode()` function does something else, not what I’d expect given that there are `mean()` and `median()`…) It’s quite easy to write a short function to calculate the mode in R:

```Mode <- function(x) { uni <- unique(x) uni[which.max(tabulate(match(x, uni)))] }```