07-ProgrammingR - Programming With Data in R
07-ProgrammingR - Programming With Data in R
You can place the data directly in your working directory to make it
easier to use. If you are not sure where your current working directory
is, you can always check your directory using command getwd().
load("births.RData")
head(births)
summary(births)
Fridays=births[which(births[,4]==5),]
Fridays13=Fridays[which(Fridays[,3]==13),]
head(Fridays13)
dim(Fridays13)
## [1] 25 5
Weekendbirths=births[which(births[,4]%in%c(6,7)),]
Weekdaybirths=births[which(births[,4]<6),]
if (mean(Weekendbirths[,5])> mean(Weekdaybirths[,5]))
{ cat("More weekend babies on average") }else {
cat("There are less weekend babies on average")
}
A typical loop:
set.seed(431)
mat43=replicate(4,sample(3,3))
mat43l=rep(0,4)
for (j in 1:4)
{mat43l[j]=max(mat43[,j])}
mat43l
## [1] 3 3 3 3
A vectorized version:
apply(mat43,2,max)
## [1] 3 3 3 3
apropos("apply")
?apply
mat43=replicate(5000,sample(30000,1000))
dim(mat43)
system.time(apply(mat43,2,max))
mat43l=rep(0,5000)
system.time(for (j in 1:5000)
{mat43l[j]=max(mat43[,j])})
Example
library(readxl)
read_excel
vec=c(1,2,3,5,7,11,13,17,19,23)
(vec^2)+ 1
(vec^2)+ 3
(vec^3)
We write a function
ExpAnd()
ExpAnd(vec=seq(4,25,3),exponent=2,addto="3")
ExpAnd(addto="4")
ExpAnd(vec=matrix(c(2,3,4,1,1,2,2,7),ncol=2),3,0)
## [,1] [,2]
## [1,] 8 1
## [2,] 27 8
## [3,] 64 8
## [4,] 1 343
Look at all the functions we have not tried yet and try
the examples.