"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

February 19, 2016

R plot examples, matrix, aggregates, conditions examples

#Create a vector from 1 to 20, Step by 2
a <- c(seq(1,20,2))
#Create a 5 X 2 Matrix
m <- matrix(a, nrow = 5, ncol = 2, byrow=TRUE)
m
#Create a 2 X 5 Matrix
m <- matrix(a, nrow = 2, ncol = 5, byrow=TRUE)
m
#transpose
t(m)
#Create Square matrix
m <- matrix(a, nrow = 2, ncol = 2, byrow=TRUE)
det(m)
#matrix multiplication, Operator %*%
m%*%m
#eigen values
eigen(m)
#svd - singular vector decomposition
svd(m)
view raw Matrix.R hosted with ❤ by GitHub
#vector with hundred elements
m <- c(seq(1,100,1))
#List all values > 10
m[m>10]
#List all values > 10 and < 50
m[m>10 & m < 50]
#List all values > 10 and !=50
m[m>10 & m!= 50]
#Conditional select from data frame
food = read.csv("protein.csv")
newdata <- food[(food$RedMeat>5),]
newdata
#Load Some Sample Data
dat <- read.table(textConnection('Group Score Info
+ 1 1 1 a
+ 2 1 2 b
+ 3 1 3 c
+ 4 2 4 d
+ 5 2 3 e
+ 6 2 1 f'))
#print summary
summary(dat)
#Aggregations
aggregate(Score~Group,dat,sum)
aggregate(Score~Group,dat,mean)
#functions
cellbillcompute<-function()
{
billdays<- c(55,10,15,33,21,33,45,66,35,25)
#max value
print(max(billdays))
#min value
print(min(billdays))
#sum of all bill days
print(sum(billdays))
#Number of days bill value > 20
print(length(billdays[billdays>20]))
}
cellbillcompute()
#Installing Packages
remove.packages(c("ggplot2", "data.table"))
install.packages('Rcpp', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)
install.packages('data.table', dependencies = TRUE)
#List all packages
data()
#Visualization Examples
carsmodel <- c("Dzire", "Vitara", "ALTO", "Gypsy", "Baleno")
sales <- c(200, 555, 424, 599, 12000)
#plot example
plot(factor(carsmodel),sales,type="o",col="green",pch=22)
#dotplot
library(lattice)
dotplot(sales~carsmodel)
#Connected Lines
dotplot(sales~carsmodel,type="b")
library(ggplot2)
qplot(carsmodel,sales)
ggplot(data.frame(carsmodel,sales), aes(carsmodel,sales)) + geom_point()
#plot for share values
library("quantmod")
getSymbols('TYC')
chartSeries(TYC, subset='last 3 months')
addBBands()
food = read.csv("protein.csv")
#Find Outliers
boxplot(food$RedMeat)
#boxplot with multiple variables
boxplot(food$RedMeat,food$WhiteMeat, food$Eggs)
#Histogram of data
hist(food$RedMeat)
#Summary
summary(food)
#heatmap
library(rgl)
dist = as.matrix(food[-1])
heatmap(dist)
view raw PlotExamples.R hosted with ❤ by GitHub
Happy Learning!!!

No comments: