R Commands
Published:
This lesson is on basic commands of R
Function
# print squares of numbers
squares = function(n) {
for(i in 1:n) {
print(i^2)
}
}
squares(5)
# add squares of numbers
squares = function(a, b) {
return(a^2 + b^2)
}
result = squares(a=5, b=5)
print(result)
# Lazy Evaluation of Function
lazyfn <- function(a, b) {
print(a)
print(b) # error only when it is needed
}
lazyfn(5)
Decision
# Check if Odd or Even
x = 6
if(x %% 2 == 0){
print("x is even")
}else{
print("x is odd")
}
x = 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else{
print("Zero")
}
Loop
for (x in 1:5) {
print(x)
}
days <- list("monday", "tuesday", "wednesday", "thursday", "friday")
for (x in days) {
print(x)
}
dice <- c(1, 2, 3, 4, 5, 6)
for (x in dice) {
print(x)
}
Charts
library(ISLR2)
Boston = ISLR2::Boston
dim(Boston)
View(Boston)
attach(Boston)
unique(Boston$rad)
table_rad = table(Boston$rad) # freqency of unique values
df = as.data.frame(table_rad)
print(df)
pie(x=df$Freq, labels=df$Var1, main="Pie")
barplot(df$Freq, names.arg=df$Var1, main="Barplot")
boxplot(age, data=Boston, main="Box Plot")
hist(Boston$age, main="Histogram")
plot(Boston$medv, type="l", main="Line")
plot(Boston$medv, type="o", main="Line and Points")
plot(x=Boston$lstat, y=Boston$medv, main="Scatter")