---
title: "R Introduction"
output: html_notebook
---

First things first, let's install some useful packages. For today, we will use the "astro" and "MClust" package.
Package installation is one of the main reasons why I love R so much! It's a one-liner with no need to ransack the web for the right/latest version compatible with current installation, etc! R takes care of that in the background.
```{r} 
install.packages("astro")
install.packages('mclust')
```

To load the packages, use the library() function.
```{r}
library(astro)
```

You can also load the packages by ticking the box in the packages tab on the right (try this for mclust if you like) -> 

Now let's also set the working directory to a path of your choice. Mine is (warning: this produces no visible output):
```{r}
setwd('/Users/cfoster/research/Rintro/')
```
Well... this produces a warning. Just paste the command into the console so that the working directory is updated properly for the duration of the talk.

Defining objects is easy. Assignment can be either using the equal "=" or arrow "<-" symbols. Double arrow is used for global variables (<<-). Here are a few examples I use.

1- Lists & data frames:
```{r}
mylist<-c('I','can','put')
myotherlist=c('whatever','I','like')
myotherotherlist=c(1,2,3)
lookadataframe=as.data.frame(cbind(mylist,myotherlist,myotherotherlist))
lookadataframe[2,3]
lookadataframe[,'mylist']
lookadataframe[1,'myotherlist']

```
It's easy to refer to the various columns by their number (starting at 1) and/or names!

2- Matrices:
```{r}
mymatrix=matrix(c(c(1,2,3),c(4,5,6),c(0,0,7)),nrow=3,ncol=3,byrow=TRUE)
print(mymatrix)
```
2- Functions:
```{r}
myfunction <- function(someparameterdefault=1,otherparameternodefault){
  if (otherparameternodefault==TRUE){
    return(someparameterdefault)
  }else{
    return(0)
  }
}
```
When you define objects, they appear in your environment tab on the upper right.
Running the function is easy:
```{r}
myfunction(someparameterdefault=20,otherparameternodefault=TRUE)
```

Usual functions like "for" loops also straightforward to use:
```{r}
for (element in mymatrix){
  print(20+element)
}
```


How about simple plots? I hear you say.

First, let's set up the notebook so that the output plots appear inline. Go to top menu, tools > Global Options... > R Markdown
and under "Show output preview in" select "Viewer Pane". Click "Apply" and "Close".

If you want to know how to use a certain function, there are always examples in the help pages. Click on the help tab on the right, then
search for "aplot". Scroll to the end of the help page. There are 4 examples in this case. I pasted pasted and slightly edited them below.

```{r}
# example #1
layout(1) #This is a single panel plot.
par("mar"=c(5.1,4.1,2.1,2.1)) #number of lines of margin to be specified on the four sides of the plot
par("oma"=c(0,0,0,0)) #the size of the outer margins in lines of text
aplot(sin, xlim=c(0,2*pi), ylim=c(-1.1,1.1), xlab=expression(theta), ylab=expression(paste('sin(',theta,')', sep='')), bgcol="lightgoldenrodyellow", main='plot title') #Plotting the sine function from 0 to 2pi.
abline(h=0, col="grey75") #Plotting the horizontal line at y=0
label("bottomleft", txt="meet the sine function", cex=2, lwd=0, bgcol=NULL)
```

And do remind me to show you how to resize and save these also!


```{r}
# example #3
layout(cbind(c(1,2),c(3,3)), widths=c(5,1)) #Defining the layout, first column has panels 1 and 2, second column has a single panel across both rows. The "widths" keyword gives the relative sizes of the columns.
par("mar"=c(0,0,0,1)) #defining inner margins
par("oma"=c(3.1,3.1,3.1,2.1)) #defining outer margins
testdata=as.data.frame(cbind(rnorm(1000), rnorm(1000), rnorm(1000)))#random set of 1000 normally distributed points (default mean = 0 and sd = 1). Notice, this creates a clickeable object in the "global environment" panel on the top right. Data.frames are awesome!
colnames(testdata)=c('x','y','z') #Naming the columns
aplot(testdata$x,testdata$y,testdata$z, pch=17, zlim=c(-1,1), xlim=c(-3,3), ylim=c(-3,3), labels=2:3)
grid() #adding a background grid
label("topleft", txt="astro:colourbar (acb)", cex=2, lwd=0, bgcol=NULL)
aplot(rnorm(1000), rnorm(1000), rnorm(1000), pch=16, zlim=c(-1,1), xlim=c(-3,3), ylim=c(-3,3), labels=1:2) #Drawing second row panel.
grid()
acb(zlim=c(-1,1), zlab="z-axis label") #Adding a colourbar as the third panel.
```

How about the fancy statistics stuff? Want to do fancy Gaussian Mixture Model analysis? Easy!

```{r}
library(mclust)
```
Let's create a clustered dataset based on the functions we saw earlier.
```{r}
kennel1=cbind(retriever=rnorm(200,mean=-1,sd=1), chiwawa=rnorm(200,mean=0,sd=1), poodle=rnorm(200,mean=6,sd=2))
kennel2=cbind(retriever=rnorm(400,mean=-5,sd=4), chiwawa=rnorm(400,mean=1,sd=1), poodle=rnorm(400,mean=8,sd=2))
kennel3=cbind(retriever=rnorm(100,mean=-10,sd=3), chiwawa=rnorm(100,mean=-2,sd=1), poodle=rnorm(100,mean=11,sd=2))
kennels=as.data.frame(rbind(kennel1,kennel2,kennel3))

layout(matrix(c(1,2,  0,3), nrow=2, ncol=2, byrow=TRUE))
plot(kennels[,c('retriever','chiwawa')], pch=16, cex=0.3) #Quick and dirty plot to see what it looks like.
plot(kennels$retriever,kennels$poodle, pch=16, cex=0.3)
plot(kennels[,c(2,3)], pch=16, cex=0.3)
```

Let's see if GMM can recover the groups?
```{r}
findclust=Mclust(kennels) #The whole GMM is one line!
summary(findclust, parameters = TRUE)
plot(findclust, what="classification")
```
So it found 3 groups with ~200, ~100 and ~400 members. Let's compare the output to the input:
clump 1 at (-1,0,6)
clump 2 at (-5,1,8)
clump 3 at (-10,-2,11)

Hey and I can even run python (SQL, Bash, etc) scripts?!
```{python}
x=12
y=3
print(x*y)
```

Ah! And to save your work (in addition to saving the file), you can save this whole workspace in a .img file:
```{r}
save.image('Rintro.img')
```


Clear your workspace now and see if it reloads everything again:
```{r}
rm(list=ls())
```

This can be reloaded later:
```{r}
load('Rintro.img')
```

You can also source files:
```{r}
source('examplefunction.r')
```

with packages/functions (e.g. in the examplefunction.r file):
```{r}
helloworld()
```


When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the *Preview* button or press *Cmd+Shift+K* to preview the HTML file).














