---
title: "Ordinal Variables in R"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```



```{r}
titanic <- read.csv("titanic.csv")
titanic <- titanic[!is.na(titanic$pclass),]
```

We can run the logistic regression by treating class as an integer:

```{r}
glm(survived~pclass, data=titanic, family=binomial)
```

Or we can treat class as a factor:
```{r}
glm(survived~factor(pclass), data=titanic, family=binomial)
```

Let's now convert `pclass` to `character` and see what happens:

```{r}
titanic$pclass = as.character(titanic$pclass)
titanic$pclass[1:10]
```

As you can see, the digits are now in quotes, indicating that R won't treat them as integers anymore.

```{r}
glm(survived~pclass, data=titanic, family=binomial)
```

This is the same as converting `pclass` to a factor.

Now, let's switch from "1" to "first class", "2" to "second class", etc:

```{r}
digits_to_words <- function(digit){
  return(switch(digit, "1"={"first class"}, "2" = {"second class"}, "3" = {"third class"}))
}

titanic$pclass_words <-as.character(sapply(titanic$pclass, digits_to_words))
```

```{r}
glm(survived~pclass_words, data=titanic, family=binomial)
```

Same thing.

Finally, let's switch back to integers

```{r}
words_to_num <- function(word){
  return(switch(word, "first class"={1}, "second class"={2},  "third class"={3}))
}

titanic$class_ordinal <-as.numeric(sapply(titanic$pclass_words, words_to_num))
```

```{r}
glm(survived~class_ordinal, data=titanic, family=binomial)
```




