###Commands and case sensitivity
###Command as an expression
1+2
###Assignment
a<-1+2
a
###OR
print(a)
####separation of command are either by ";" or a new line
a<-1+2;print(a)
####OR alternatively
{
a<-1+2
print(a)
}
####Case sensitivity
A<-2+5
A
a
A
####Data permanency and removing objects
###listing objects
b<-8-2
c<-20/5
d<-7+19
ls()
##OR
objects()
####Removing objects
rm(a,d)
ls()
#######Vectors and assignment
####Concatenating command
#####Assignment statement
x<-c(10.4,5.6,3.1,6.4,21.7)
x
#####OR
assign("y",c(10.4,5.6,3.1,6.4,21.7))
y
#####OR
c(10.4,5.6,3.1,6.4,21.7)->x
x
###Expression not assigned
1/x ###computes the recipricals of the vector x
#####Further assignments
y<-c(x,0,x) ###creates a vector of 11 entries, consisting of two copies of x
####with a zero in the middle and assigns them to y
y
######Vector Arithmetic
v<-2*x+y+1
v
length(x)
sum(x)
max(x)
min(x)
mean(x)
sum(x)/length(x)
var(x)
variance<-sum((x-mean(x))^2)/(length(x)-1)
variance
sqrt(variance)
#####Generating regular sequences
####Colon operator
1:30 ###this is a sequence of values from 1 to 30
2*1:15
##put
n<-10
####and compare the sequences
1:n-1
###and
1:(n-1)
###Generating sequence backwards
30:1
###
seq(1,30)
###same as 1:30
####OR
seq(from=1,to=30)
#####OR
seq(to=30,from=1)
s<-seq(-5,5,by=0.2)
s
####OR
s2<-seq(length=51,from=-5,by=0.2)
s2
seq(1,10,by=2)
#####REPLICATION
s3<-rep(x,times=5)
s3
rep(4,times=7)
#####Logical vectors
w<-x>10
w
z<-x<=5
z
temp<-y==0
####intersection
x&y
w&z
#####union
w|z
x|y
####Negation
!w
!z
#####Missing values
x<-c(10.4,5.6,3.1,NA,6.4,21.7)
x
[Link](x)
x==NA
0/0
Inf-Inf
[Link](y)
####character vectors
ast<-c("john","jane","cate")
ast
x<-c("10.4","3")
x
labs<-paste(c("X","Y"),1:10,sep="")
labs
######Index Vectors
####A logical vector
x<-c(-3,10.4,5.6,3.1,6.4,NA,21.7,9.6,2.1,13.3,-1.8,3.4)
x
y<-x[]###creates an object y which contain non missing values of x
y
z<-(x+1)[()&x>0]###creates z and places it in the value of the vector x+1
####for which the corresponding values of x are both non
missing and positive
z
#####A vector of positive integral quantities
x[6] ###6th component of x
x[1:10] ### first ten elements of x
c("x","y")[rep(c(1,2,2,1),times=4)] ##3produces character vector of length 16
####A vector of negative integral quantities
y<-x[-(1:5)] ###excludes the first 5 values in x
y
####A vectoe of character strings
fruit<-c(5,10,1,20)
names(fruit)<-c("orange","banana","apple","peach")
lunch<-fruit[c("apple","orange")]
lunch
fruit
####index vector on the recieving end of an assignment
x[[Link](x)]<-0 ###replaces any missing value in x by zero
x
y[y<0&]<-(-y[y<0]) ###gives absolute values of y
y
y<-abs(y)
y
x <- c(1,3,5,7,NA,2,4,6)
x[x>=5&] <- c(1:8)[x>=5&]
x[x<5&] <- (c(1:8)*10)[x<5&]
x[subset1] <- which(subset1)
x[subset2] <- 10*which(subset2)
x
#####Objects
####empty modes
character(0)
numeric(0)
####coercion
z<-complex(real=100,imag=100)
z
mode(z)
mode(z)<-"numeric"
t<-complex(real=rnorm(100),imag=rnorm(100))
t
mode(t)
mode(t)<-"numeric"
length(t)<-10 ####trancates t down to the first 10 elements
length(t)<-100 ###lengthens it back to 100 by adding NA's
mode(t)<-"character"
z<-0:9
z
###puting z as a character vector
digits<-[Link](z)
digits
###reconstructing to numeric again
d<-[Link](digits)
d
###Changing the length of an object
##empty object
e<-numeric()
e
###adding new component
e[3]<-17 ###vector of length 3 where first two elements are NA's and third element
is 17
e
e[(3:5)]<-c(17,21,5)
e
#####scan function
f<-scan()
f[5]<-7
f
###truncation of size object require an assignment
alpha<-1:10
alpha<-alpha[2*1:5]
alpha
####the attribute() and attr() functions
attr(z,"dim")<-c(2,5)
z
####class of an object
class(alpha)
class(z)
###unclass
unclass(z)
x<-[Link](1:10,11:20)
x
class(x)
unclass(x)
####ordered and unordered factors
####unordered factors
state<-
c("tas","sa","qld","nsw","nsw","nt","wa","wa","qld","vic","nsw","vic","qld","qld","
sa",
"tas","sa","nt","wa","vic","qld","nsw","nsw","wa","sa","act","nsw","vic","vic","act
")
state
###creatin state as factor
statef<-factor(state)
statef
###OR
statef<-[Link](state)
statef
###sorting in alphabetical order
sort(statef)
###finding out the levels of the factor
levels(statef)
#####Ordered factors
house<-
[Link](c("small","small","big","small","big","big","big","small","big","small","
small","small"))
house
###using ordered() function
house<-ordered(house,c("small","big"))
house
###Generating factor levels
gl(2, 8, labels = c("Control", "Treat"))
#####The tapply() function
incomes<-
c(60,49,40,61,64,60,59,54,62,69,70,42,56,61,61,61,58,51,48,65,49,49,41,48,52,46,59,
46,58,43)
incomes
length(incomes)
####calculating sample mean income for each state
incmeans<-tapply(incomes,statef,mean)
incmeans
####Calculating standard errors of state income means
###function calculating standard errors
stderr<-function(x) {sqrt(var(x)/length((x)))}
stderr
#calculating standard errors
incster<-tapply(incomes, statef, stderr)
incster
##Splitting tax accountants by both state and sex
##Two ways
sex<-[Link](rep(c("F","M"),15))
sex
##OR First 15 female and last 15 male
sex<-gl(2,15,labels = c("F","M"))
sex
###Now calculating means according to both state and sex
tapply(incomes,list(statef,sex),mean)
#####Arrays
z<-1:1500
dim(z)<-c(3,5,100)
dim(z)
z
#####Indexing
z[,,]
z[2,1,1]
z[3,2,1]
z[3,4,1]
####index array
x<-array(1:20,dim=c(4,5)) ##4x5 array
x
i<-array(c(1:3,3:1),dim=c(3,2)) ##3x2 index array
i
x[i] ### extracts those elements
x[i]<-0 ### replace those elements with zero
x
h<-1:24
g<-array(h,dim=c(3,4,2))
g
###Same as
g<-h
dim(g)<-c(3,4,2)
g
g<-array(0,c(3,4,2))##makes g an array of all zeros
#####Matrix
x<-c(1,2,3,4,5,6,7,8,9)
y<-c(2,4,8,7,9,1,3,5,6)
X<-matrix(x,nrow=3,ncol=3,byrow = T)
X
Y<-matrix(y,nrow = 3,ncol = 3)
Y
####OR
x<-array(x,dim=c(3,3))
x
crossprod(X,Y) ###same as
t(X)%*%Y
solve(Y) ####inverse of Y
eigen(X)###Eigen values and eigen vectors of X
det(X)
diag(X)##Determinant of X
cbind(x,y)
rbind(x,y)
Y<-cbind(1,x,y)
Y
##### frequency tables from factors
state<-c("tas","sa","nsw","nt","wa","tas","wa")
newstate<-factor(state)
incomes<-c(60,49,40,61,64,60,59)
statetabl<-table(newstate)
statetabl
statetabl<-tapply(newstate,newstate,length)
statetabl
incomef<-factor(cut(incomes,breaks=35+10*(0:7)))
table(incomef,newstate)
#list
lst<-list(name="Fred",wife="Mary",[Link]=3,[Link]=c(4,7,9))
lst
lst$name
lst$[Link][3]
lst[["name"]]
#### constructing and modifying lists
lst[5]<-list(matrix=matrix(1:9,ncol=3))
lst[5]
#data frames
state<-
c("tas","sa","qld","nsw","nsw","nt","wa","wa","qld","vic","nsw","vic","qld","qld","
sa",
"tas","sa","nt","wa","vic","qld","nsw","nsw","wa","sa","act","nsw","vic","vic","act
")
###creatin state as factor
statef<-factor(state)
sex<-gl(2,15,labels = c("F","M"))
incomes<-
c(60,49,40,61,64,60,59,54,62,69,70,42,56,61,61,61,58,51,48,65,49,49,41,48,52,46,59,
46,58,43)
accountants<-[Link](State=state,Income=incomes,Gender=sex)
accountants
attach(accountants)
accountants$State<-30:1
accountants$State
###Functions
f1 <- function(a, b) {
# This function returns the maximum of two scalars or the
# statement that they are equal.
if([Link](c(a,b))){
if(a < b) return(b)
if(a > b) return(a)
else print("The values are equal")
}
else print("Character.")
}
f1(4,7)
f1(pi,exp(1))
f1(0,exp(log(0)))
f1("Stephen","Christopher")
mortgage <- function(A = 100000, r = 6, y = 30){
P <- A*r/1200/(1-(1+r/1200)^(-12*y))
return(round(P, digits = 2))
}
mortgage()
mortgage(200000,5.5) # use default 30 year loan value
mortgage(y = 15)
###Plots
data(trees)
attach(trees)
plot(Height,Volume)
?plot()
x<-Height
y<-Volume
plot(x,y,xlab="Height",ylab="Volume",main="Trees data",type="l",col="red")
curve(sin(x),from=0,to=2*pi)
?abline()
abline(h=1,col="blue")
curve(sin(x),from=0,to=2*pi)
par(mfrow=c(3,2))
curve(cos(x),from=0,to=pi)
data(mtcars)
attach(mtcars)
mtcars
mean(hp)
var(mpg)
cor(wt,mpg)
table(cyl)
length(cyl)
barplot(table((cyl)/length(cyl)))
data(faithful)
attach(faithful)
faithful
hist(eruptions)
?hist()
hist(eruptions,breaks=18)
stem(eruptions)
boxplot(waiting)
boxplot(faithful)
qqnorm(waiting)