This script shows how use principal component analysis to extract a single component from multiple codings of a same item. In this case, our running example will be annotations of the emotions generated by a set of images.

First, we read the data, which contains 20 annotations along a series of emotions for a total of 24 images.

```{r}
codings <- read.csv("../data/image-codings.csv", stringsAsFactors = F)
head(codings, n=6)
```

For the purposes of simplifying the analysis, we will now collapse all annotations for each image into a single average by emotion:

```{r}
library(dplyr)
agg <- codings %>% group_by(image) %>%
  summarise_all(mean)
```

This is how you can visualize the data using a heatmap:

```{r}
mat <- agg %>% 
  select(-image) %>%  # keep only the numeric variables
  data.matrix() # convert to matrix
heatmap(t(mat)) # transpose to help visualization
```

Now let's run PCA:

```{r}
pca <- princomp(mat)
pca
```

Exploring the loadings for the first two components:
```{r}
# loading for first two components
round(pca$loadings[,1:2],2)
```

Using a scree plot to explore how many dimensions to keep?

```{r}
screeplot(pca, 
          main="Screeplot: Relative importance of\neach different PC",
          las=2)
```

