---
title: "Data Analysis in RStudio"
output:
  html_document:
    df_print: paged
  html_notebook: default
  word_document: default
  pdf_document: default
---

# Setup

1. Install R. [Digital Ocean](https://www.digitalocean.com/community/tutorials/how-to-install-r-on-ubuntu-20-04) has a nice guide on this (and many other things Linux-related, they are one of my preferred documentation sources)
2. Install RStudio. The [RStudio Downloads Page](https://www.rstudio.com/products/rstudio/download/) has a Debian package you can download. Install with `sudo dpkg -i <pkgname>.deb`
3. Add data.table with Tools->Install Packages..., enter `data.table`
4. Install texlive full with `sudo apt install texlive-full` to enable PDF output

# Datasets
Load profiles come from [http://wzy.ece.iastate.edu/Testsystem.html](http://wzy.ece.iastate.edu/Testsystem.html)

# Analysis

## Load Data
```{r}
feeder_a <- read.csv("feeder_a_data.csv")
names(feeder_a)
```

There's a lot of columns here from the different smart meters. 
Let's just take the total power

```{r}
fa <- feeder_a[,c("Month","Day.of.Week","Hour","Elapsed.Days","Total.Power")]
```

Take a quick look at the loaded data. You can also use the "Environment" tab, 
but this won't show up in the notebook

```{r}
head(fa)
```

## Visualize Data
```{r}
hist(fa$Total.Power)
```
How to do arithmetic with data frame columns

```{r}
fa$b12 <- feeder_a$Bus.1001 + feeder_a$Bus.1002
```

```{r}
mean(fa$Total.Power)
```

There's a convenient command to print summary stastics for each column

```{r}
summary(fa)
```

Plot the power over time. Yikes! There's a lot of data here? Just how long is it?

```{r}
plot(fa$Total.Power,type="l")
```
A whole year! That's too much!

```{r}
max(fa$Elapsed.Days)
```

We can plot just the first week by taking a subset of rows

```{r}
plot(fa[fa$Elapsed.Days<=7,"Total.Power"],type="l")
```


```{r}
names(fa)
```

## How to Replace Excel Pivot Tables with R Data Tables

```{r}
require(data.table)
```


```{r}
ta <- as.data.table(fa)
```

Let's look at how much power is used per day of week (1 = Sunday). People
are a little lazy on Mondays

```{r}
ta[,mean(Total.Power),by=Day.of.Week]
```

Now let's look at power vs month. It looks like air conditioning loads 
cause a peak in July

```{r}
ta[,mean(Total.Power),by=Month]
```
Finally, let's look at power vs time of day. The peak is at noon, though
in some regions/seasons it is common two have two peaks in mornings/evenings

```{r}
ta[,mean(Total.Power),by=Hour]
```

