302 R Codes


Function R Note
Clean up vars rm()
Assign <-, = Are they exactly the same?
Concatenate (Vectors) c()
Add (Concatenated Vectors) +
Add to library library()
Set Seed set.seed()
Install Package install.packages("") Extra
Print print()
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 head of a data frame head()
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

Data Type

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)
Like dicts.
> f1 <- factor(c(rep("A", 3), rep("B", 3)))
> f1
[1] A A A B B B
Levels: A B
> c(f1)
[1] 1 1 1 2 2 2
> f1 + v1 #v1 is a vector
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[1] <- "C"
How to change level order?
# By default, level order is alphabetical
f3 <- factor(f2, levels = c("C", "B", "A"))
How to add labels?
f3 <- factor(f2, levels = c("C", "A", "B"), labels = c("Clementines", "Apples", "Bananas"))
How to go back to alphabetical order?
barplot(table(factor(f3, levels = levels(f3)[order(levels(f3))])))
# Pareto
barplot(table(factor(f3, levels = levels(f3)[order(-table(f3))])))