# 302 R Codes

## Function

Function R Note
rm(list=ls())
Clean up vars rm()
Assign <-, = Are they exactly the same?
Concatenate (Vectors) c()
Set Seed set.seed()
Install Package install.packages("") Extra
Print print()
scale_y_log10()
Multiply *
Calculate Dot Product %*% Must be of same size
Show Structure (= Type + Value) str() "str" does not mean "string" here
Show Type str() 1st result is type of var
Convert to character as.character()
Convert to numeric as.numeric()
Replicate vectors rep()
Convert to uppercase toupper()
Show all distinct values factor()
Show level levels()
Show table table()
Drop extra level droplevels()
Create a data frame data.frame() e.g. df1 <- data.frame(treatment = f1, response = v1)
Show tail of a data frame tail()
Show attr of a data frame \$, with()
Show ... with ... with()
Show summary of data summary()
Add new attr in df1\$newAttr <- df1\$attr * 2.54 Alt: df1 <- within(df1, { newAttr <- attr * 2.54 })
Apply tables tapply() e.g. with(df1, tapply(newResponse, treatment, mean))
R2 from line 28

Name In R
Uniform unif

Name In R
Numeric num
Character chr

## Statictic Description

Name In R Note
Q-Plot qplot()
Box Plot boxplot() e.g. boxplot(newResponse ~ treatment, data=df1)
Histogram hist()
Vector algebra w/ diff len in R
e.g. c(1, 2, 3) + c(4, 5) = c(1, 2, 3) + c(4, 5, 4) = c(5, 7, 7)
Factor
Like dicts.
```> f1 <- factor(c(rep("A", 3), rep("B", 3)))
> f1
 A A A B B B
Levels: A B
> c(f1)
 1 1 1 2 2 2
> f1 + v1 #v1 is a vector
 NA NA NA NA NA NA
Warning message:
In Ops.factor(f1, v1) : '+' not meaningful for factors
```
How to add a level in factor?
# There were only 2 levels: A & B. And we want to add level C.
```f2 <- factor(f1, levels = c("A", "B", "C"))
f2 <- "C"
```
How to change level order?
```# By default, level order is alphabetical
f3 <- factor(f2, levels = c("C", "B", "A"))
```
```barplot(table(factor(f3, levels = levels(f3)[order(levels(f3))])))