sheet praktikum komstat ii

2
FUNCTION IN R General form function( arglist ) expr return(value) norm<-function(x) sqrt(x%*%x) norm(1:4) #panjang vector (function(x,y){z<- x^2+y^2;x+y+z}) (0:7,1) #outputnya x+y+z #x+y+z => (0:7)+1+(0:7)^2+1^2 Fgs untuk mengisi NA pd matriks sebesar rxcxp miss<-function(A,p) {nb<-nrow(A) nk<-ncol(A) na<-round(nb*nk*p) bb<- sample(1:nb,na,replac e=T) kk<- sample(1:nk,na,replac e=T) A[bb,kk]<-NA return(A)} A<- matrix(rnorm(20),4,5) miss(A,0.2) #Buat matriks yang NA nya sebanyak rxcxp mis<-function(A,p) {nb<-nrow(A) nk<-ncol(A) Am<- matrix(rbinom(nb*nk,1 ,p),nb,nk) Am1<- ifelse(Am==1,NA,1) Anew<-A*Am1 return(Anew)} #peluang munculnya sukses 1 sebesar p A<- matrix(rnorm(20),4,5) mis(A,0.8) #Multiple Regression reg<-function(A) {if(!is.matrix(A)) {stop("input must be on matrix")} y<-A[,1] xx<-A[,-1] satu<-rep(1,nrow(A)) x<-cbind(satu,xx) colnames(x)<- paste("x",1:ncol(A),s ep="") b.est<-solve(t(x)%* %x)%*%(t(x)%*%y) rownames(b.est)<- paste("b",0: (nrow(b.est)- 1),sep="") fitted.value<-x%* %b.est resi<-(y- fitted.value) list(beta.est=b.est,f it.val=fitted.value, residuals=resi)} pend<- c(3.5,3.2,3,2.9,4,2.5 ,2.3) biaya<- c(3.1,3.4,3,3.2,3.9,2 .8,2.2) warung<- c(30,25,20,30,40,25,3 0) A<- cbind(pend,biaya,waru ng) reg(A) reg(A)[1] #beta.est aja hasil<- lm(pend~biaya+warung) hasil #koefnya aja summary(hasil) anova(hasil) CONTROL FLOW General form if(cond) expr if(cond) cons.expr else alt.expr for(var in seq) expr while(cond) expr repeat expr break next #fungsi cat hampir sm kayk paste for(n in c(2,5,10,20,50)) for(n in c(2,5,10,20,50)) {x<-rnorm(n) cat(n,": ", sum(x^2),"\ n",sep="")} 2: 5: 50: #isi f: acdbeeabcde (missal) f<- factor(sample(letters [1:5],10,replace=TRUE )) for(i in unique(f)) print(i) #for juga berlaku untuk karakter x<-9; jumlah<-0 while(x<10) {jumlah<- jumlah+x;x<-x+1} jumlah=9 x=10 B<-function(A) {n<-nrow(A) for(i in 1:n) {A[i,i]<-1 A[i,n-i+1]<-1 } B<-A return(B) } A<- matrix(rep(0,25),5) B(A) [,1] [,2] [,3] [,4] [,5] [1,] 1 0 0 0 1 [2,] 0 1 0 1 0 [3,] 0 0 1 0 0 [4,] 0 1 0 1 0 [5,] 1 0 0 0 1 #Mencari Mean Median Modus three.M<-function(x) { n<-length(x) m1<-sum(x)/n y<-sort(x) p<-n/2 if(p%%1==0){m2<-(y[p] +y[p+1])/2} else {m2<- y[ceiling(p)]} z<-min(x):max(x) pz<-1:length(z) for(i in 1:length(pz)) {a<- ifelse(x==z[i],1,0) pz[i]<-sum(a) } mpz<-max(pz) impz<- ifelse(pz==mpz,1,0) m<-z*impz m3<-m[m!=0] list(mean=m1,median=m2,m odus=m3)} x<- c(5,8,6,9,10,6,4,8,3,7,7 ,11,2,9,6) three.M(x) PLOT IN R General Form: plot(x, y, …) Possible type to be drawn “p” for points “l” for lines “b” for both “c”for the lines part alone of “b”/putus2 “o” for overplotted “h” for histogram like “s” for stair steps “S” for other steps/horizontal dl “n” for no plotting plot(sin,-pi,2*pi) abline(h=0, col=2, lty=2, lwd=3) plot(table(rpois(100,5)) ,type="h", col="red", lwd=10, main="rpois(100,lambda=5 )") plot(x<-sort(rnorm(47)), type="s", main="plot(x,type=\"s\") ") points(x,cex=.5,col=2) #dianggap petik 2 gitu supaya jadi judul s nya ada petik 2 nya x<-1:25 y<-rnorm(25,4,2) #ragamnya 4, sd nya makannya 2 plot(x,y, pch="w", main="W") Create some programs to make the graph, using 100observation of X χ 2 ( 4) set.seed(14) x<-rchisq(100,df=4) #biasanya y nya frekuensi hist(x, freq=FALSE, ylim=c(0,0.2)) curve(dchisq(x,df=4),col =2, lty=2, lwd=2, add=TRUE) #add nya ditimpa plot sblmnya QQ normplot qqnormal<-function(data) {qqnorm(data) qqline(data, col=2) } x<-runif(300,0,5) qqnormal(x) y<-rlnorm(500,3,2) qqnormal(y) 0.5 1 2 0 5 10 15 20 25 30 35 Guinea P igs'Tooth Grow th VitaminC dose mg tooth len g th data(ToothGrowth) View(ToothGrowth) #liat datanya boxplot(len~dose, data=ToothGrowth, boxwex=0.25, col="yellow", main="Guenia Pigs'Tooth Growth", xlab="Vitamin C Dose(mg)", ylab="Tooth Length", xlim=c(0.3,3.5), ylim=c(0,35)) data(VADeaths) dotchart(VADeaths, main="Death Rates in Virginia-1940") #tranpose t(VADeaths) dotchart(t(VADeaths), main="Death Rates in Virginia-1940") D eath R ates in V irginia - 1940 D eath R ates in Virginia - 1940 a function to make Normal density plot with n= 10,25,50,75,100,150,200 in one window a<-function(n) {p<-ceiling(length(n)/2) windows() split.screen(c(2,p)) for(i in 1:length(n)) {screen(i) x<-rnorm(n[i]) hist(x,freq=FALSE,main=N ULL) dd<-function(x) dnorm(x) curve(dd(x),col=2,lty=2, lwd=2, add=TRUE) title(paste("Normal Plot n=",n[i]))}} n<- c(10,25,50,75,100,150,20 0) a(n) MATHEMATICS IN R General form : union(x,y) intersect(x,y) setdiff(x,y) setequal(x,y) is.element(el, set) or el %in% set #is.element(el,set) true false apakah el ada di set > x<-1:20; y<-19:22 > union(x,y) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 > setdiff(x,y) #element x yg gada di y 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 > intersect(x,y) 19 20 > setdiff(y,x) 21 22 > setequal(union(x,y),c(setd iff(x,y), intersect(x,y), setdiff(y,x))) => TRUE sstr<c("c","ab","B","bba", "c",NA,"@","bla","a","Ba", "%") > sstr[sstr %in% c(letters, LETTERS)] #cari yg TRUE aja [1] "c" "B" "c" "a" > sstr[!sstr %in% c(letters, LETTERS)] [1] "ab" "bba" NA "@" "bla" "Ba" "%" "%w/o%"<-function(x,y) x[! x %in% y] > (1:10) %w/o% c(3,7,12) #sama kayak setdiff [1] 1 2 4 5 6 8 9 10 > setdiff((1:10), c(3,7,12)) #Equal nya eqs<-function(x,y) {nx<-length(x) ny<-length(y) a<-NULL for ( i in 1:nx) {for(j in 1:ny) {if(x[i]==y[j]) a<- c(a,x[i])}} f<-as.vector(a) hasil<-unique(f) return(hasil) } eqs(4:1,3:5) =4 3 #Cari yang beda difs<-function(x,y) {nx<-length(x) ny<-length(y) a<-NULL for ( i in 1:nx) {for(j in 1:ny) {if(x[i]==y[j]) a<- c(a,x[i])}} f<-as.vector(a) f1<-unique(f) hasil<-x[x!=f1] return(hasil)} difs(4:1,3:5) = 2 1 difs1<-function(x,y) {nx<-length(x) ny<-length(y) a<-NULL for ( i in 1:nx) {for(j in 1:ny) {if(x[i]==y[j]) a<- c(a,x[i])}} f<-as.vector(a) f1<-unique(f) f2<-sort(f1) d<-x for(i in 1:length(f2)) {e<-d/f2[i] e1<-ifelse(e==1,0,1) d<-e1*d} ns<-ifelse(d==0,0,1) tx<-ns*x dd<-sort(tx[tx!=0]) return(dd)} difs1(4:1,3:5) = 1 2 Grafik sin si dan cos si x<-seq(-4,4,len=101) y<-cbind(sin(x),cos(x)) matplot(x,y,type="l",xax t="n", main=expression(paste(pl ain(sin)*phi,"and ", plain(cos)*phi)), ylab=expression(paste("s in"*phi,"cos"*phi)), xlab=expression(paste("P haseAngel",phi)), col.main="blue") axis(1,a=c(-pi,-pi/ 2,0,pi/2,pi), labels=expression(-pi,- pi/2,0,pi/2,pi)) Turunan deriv(y~sin(x^2),"x",fun c=TRUE) D(expression(sin(x^2))," x") deriv(y~sin(cos(x)*y),c( "x","y"),func=TRUE) D(expression(sin(cos(x)* y)),"x") D(expression(sin(cos(x)* y)),"y") #default order=1 DD<- function(expr,name,order =1) {if(order<1) stop("'order'must be >1") if(order==1) D(expr,name) else DD(D(expr,name),name,ord er-1)} DD(expression(x^9),"x",2 ) #diminus ordernya DD(expression(x^9),"x",1 0) #0 hasilnya lah kan pangkatnya 9 Integral integrate(dnorm,- 1.96,1.96) f<-function(x) {1/((x+1)*sqrt(x))} #isi integrate adalah fungsi integrate(f,lower=0,uppe r=Inf) #manfaatkan determinan A<-cbind(- 1,c(1,2,0),0:2) det(A) =saling bebaS solve(A,rep(0,3)) #hasilnya 0 semua berarti saling bebas, inget solve(A,B) dengan hasilnya berupa x nya #3 manfaatkan akar ciri, saling bebas akar cirinya gak ada yang 0 eigen(A)[1] #kalo 1 maka list pertama dengan akar ciri aja #LA=I L=[] A 3x2 A nya dipisah jadi A1 dan A2 A1 nya 2x2 nonsingular LL<-function(A) {nb=nrow(A) nk=ncol(A) if(nb<=nk) stop("nrow>ncol") A1<-A[1:nk,] A1i<-solve(A1) L<-cbind(A1i,0) L} A<-cbind(c(1,- 1,3),c(1,0,-1)) L<-LL(A) L [,1] [,2] [,3] [1,] 0 -1 0 [2,] 1 1 0 L%*%A [,1] [,2] [1,] 1 0 [2,] 0 1 RANDOM GENERATOR IN R 1-pt(1:5,df=1) qt(0.975,df=c(1:10,20,50 , 100, 1 000) ) #functionnya terbuka x nya plot(function(x) dt(x,df=3,ncp=2),-3,11, ylim=c(0,0.32),main="Non -central t-Density", yaxs="i") z0<- rchisq(100,df=0,ncp=2) stem(z0) #direct transf x<-runif(10) #Y~U(3,6) #Y=5X+3~U(3,6) Y<-5*x+3 #indirect transf Simulate a random sample from the distribution with density f Y ( y )=3 y 4 ; 1 yy<-function(n,Fi) { u<-runif(n) y<-Fi(u) y} Fi<-function(x) {y<-(1- x)^(-1/3)} y<-yy(100,Fi) hist(y,prob=TRUE, main=expression(f(y)==3* y^(-4))) ty<-seq(0,20,0.01) lines(ty,3*ty^(- 4),col=2) Fi<-function(x) {y<- (log(x)/(-4)} y<-yy(100,Fi) hist(y,prob=TRUE, main=expression(f(y)==4* e((-4)*x))) ty<-seq(0,20,0.01) lines(ty,4*exp((- 4)*ty),col=2) Assume we have r.v with pdf f X ( x )=θe θx ; Simulate a random sample from the distribution above using invers transform method with θ=4, and prove that the transformation function is X= ln ( U) θ xe<-function(n,fxu) { u<-runif(n) x<-fxu(u) x } f<-function(y) {x<-(- log(y)/4)} x<-xe(1000,f) hist(x,prob=TRUE, main=expression(f(x)==4* e^((-4)*x))) tx<-seq(0,20,0.01) lines(tx,4*exp((- 4)*tx),col=2) Simulate a random sample from the distribution with density f Y ( y )=3 y 2 ; 0< using Acceptance- Rejection Method xx<-function(x0,x1,n,f) { xi<- seq(x0,x1,length=1001) F<-max(f(xi)) k<-0 #banyak bil yg diterima j<-0 #iterasi hasil<-numeric(n) #numeric 0 sebanyak n while(k<n) {x<-runif(1,x0,x1) j<-j+1 y1<-runif(1,0,F) y2<-f(x) if(y2>=y1) {k<-k+1 hasil[k]<-x }} list(x=hasil,iterasi=j)} f<-function(x) 3*x^2 xs<-xx(0,1,100,f) hist(xs[[1]],prob=TRUE,m ain=expression(3*x^2),xl ab="x") tx<-seq(0,1,0.01) lines(tx,f(tx),col=2) Simulate a random sample from the Beta(2,2) distribution with density f Y ( y )=6 y ( 1y 0< y<1 using Acceptance-Rejection Method f2<-function(x) 6*x*(1- x) xs<-xx(0,1,100,f2) hist(xs[[1]],prob=TRUE,m ain=expression(6*x*(1- x)),xlab="x") tx<-seq(0,1,0.01) lines(tx,f(tx),col=2) OBJECT ORIENTED PROGRAMMING Classes in R S3 class→ almost in list structure For defining new class : class(obj) <- "class.name" S4 class→ higher programming For defining new class : setClass("class.name", representation(x="type") ,prototype(x="...")) Class: Populasi dr object S3 berupa list S4 lebih rumit S3 Classes Create an object of class “human” that consist the height, weight, & name. Height : 2.54 × 12 × 6 / 1 Weight : 180/2.2 Name : James jim<- list(height=2.54*12*6/10 0,weight=180/2.2, names="James") class(jim)<-"human" class(jim) [1] "human" > jim $height [1] 1.8288 $weight [1] 81.81818 $names [1] "James" attr(,"class") [1] "human" col<- list(CyamComp=0,MagentaC omp=0,YellowCOmp=0,Black Comp=100, Colour="Black", Type="CMYK") class(col)<-"colour" col $CyamComp [1] 0 .. $Type [1] "CMYK" attr(,"class") [1] "colour" Constructing new S4 classes A class representing codons (triplets of nucleotides) setClass("triplets", representation(x="charac ter"), prototype(x="UAG")) Construction of objects of the “triplets” class seq0 <- new("triplets"); # prototype is called, UAG aja. Kalo seq byk. seq <- new("triplets", x = c("AUG","CCA","CCA","GAA ","UGA","CCA")); typeof(seq) = S4 Assume we have a simple class with two slots below track <- setClass("track",slots = c(x="numeric", y="numeric")) with an object from the class t1 <- track(x = 1:10, y = 1:10 + rnorm(10)) Create a new "trackCurve“ by adding one more slot from the class before trackCurve <- setClass("trackCurve",sl ots = c(smooth = "numeric"), contains = "track") t1s <- trackCurve(t1, smooth = 1:10) OO programming in R: classes and methods Fungsi yg digunakan untuk mengotak ngatik objek tersebut. We can make general functions, that behave differently with different obj. In R we need: 1.A generic function: what we want to do? 2. A method: how we do it with an object of a specific class ? Method in S3 class→ almost in printing method, summarizing method, and plotting method For defining method in S3 class making function: function(...){...} Method in S4 class For defining method in S3 class : setMethod("method","clas s.name", function(...){...}) Difine a method for printing the “human” class jim<- list(height=2.54*12*6/10 0,weight=180/2.2, names="James") class(jim)<-"human" print.human<- function(x,...) {cat("name:", x$name, "\ n") cat("height:", x$height, "meters", "\n") cat("weight:", x$weight, "kilograms", "\n")} >print(jim) name: James height: 1.8288 meters weight: 81.81818 kilograms

Upload: oktarina-safar-nida

Post on 05-Sep-2015

217 views

Category:

Documents


4 download

DESCRIPTION

Sheet Ujian Komputasi Statistik

TRANSCRIPT

FUNCTION IN RGeneral formfunction( arglist ) expr return(value)norm