You are on page 1of 15
# Use CTRL + SHIFT + C to add # to miltiple Lines # Use CTRL + ENTER to run multiple lines after selecting them R.version if (Irequire("dplyr")) { instal. packages ("dplyr", dependencies = TRUE) Library (dplyr) , Af (Irequire(*stats")) { install.packages("stats", dependencies = TRUE) Library(stats) } Af (Irequire("sumarytools")) { install. packages("summarytools", dependencies = TRUE) Library(surmarytools) i Af (Irequire(*xlsx")) { install.packages("x1sx", dependencies = TRUE) Library(xlsx) AF (Irequire("psyeh")) ( install.packages("psych", dependencies = TRUE) require( psych) AF (Irequire(“tseries")) { i install packages("tseries*, dependencies = TRUE) require(tseries) Af (lrequire("car")) { install.packages("car", dependencies = TRUE) require(car) Af CIrequire(*Imtest")) { install. packages("Intest”, dependencies = TRUE) require(intest) } Af (Irequire(*sandwich")) { install.packages("sandwich", dependencies = TRUE) Library( sandwich) erent ona (ROJQLEA + voutach( )) cbiigu. Beenie) ~domnir ide NaBase <- read.x1sx( "FORMATIONS, xlsx", sheetIndex = 1) Ge ALUN Viewnasase) SeRAUaSS ic PP mototion pdiuntijique options (*scipen"=50, “digits"=5) 12.2. Sumary statistics © MOM Lok JOLLA Mmoluy #To get mean,median, 25th and 75th quartiles,min,max summary (MaBase) #0 get additional info on sd, mad (median absolute deviation), skew, kurtosis, se (sd/n*@.5) Library(psych) describe(MaBase) a.2q Pout histoqnomne hist (MaBase$FormationB) a eR as Be nae enone -cuidane. a eb ee mF ayvartest <- var.test(MaBase$formationA, MaBase$Formation8, data = Nabase) myvartest, = cu ( YuX, dOcO” Mmobor, #To identify whether the null of equality of variance is rejected BIN c- ifelse(myvartest$p.valuecd.05, FALSE,TRUE) > VoL HTo-test-the-equality-of means (with equal variances if BINEL=TRUE oF unequal “rp gouie variances if BIN-0=FALSE) E.test(NaBase$FormationA, MaBase$Formation®, data = MaBase, var.equal Wo: Bar Mb > Pa-He0 Oo te encorae MATH > Ha-jp $0 ch binfetinan be #4 Read Data with Library(xlsx) which is an alternative to library(readxl) MaBasel <- read.xlsx("cegsal2-x1sx", sheetIndex = 1) # Let us select only the numerical variables Library(“eplye") dp <-Select if(MeBaset, is.numersc) i Micw(0a) L perme: de puendin. Lg. Ler clommuby wstatDes + excel export | eQuuanbolo.tue sunmary(0B) Out wn funible vate seerter statbes + exéel export Qu’om ret Iorary(sumarytools) Be ee States <-sumarytools::deser(08)} POnne Lu» mimo ‘print(statDes, short = FALSE) | AYO Qu Library (xlsx) * Bescube mud un Pour compet wricedan(statesy files laa gheetane Sheet col.names=TRUE, IE, append=FALSE) JUN Fichwtn, LLCLL CON LEQ Lon Ae. MN en Cotes thon tha excel export Librarytpsyeh) > OWjiCh0 UL COMFIEIe POW) ChOg| nit Ly ny ( > Ot GOwM out < conmatest(O8, y = NULL, use = VO ALN) mpLthOw OL tov Fe Sguttese metiade' pearson abjsteholsalpb=-8, ASTID yy gh int(out, short = FALSE) ———. : gearsprsntiouts store Tcqutsryroutar™ pee ct VISIOMNLA Tertiary NOW NS? CoLOANL Se Goufccuunt Ubrory(rles) screetcorrtaxist, sheettme="sheeti”, CLL Cou COLbien. pr ee" Col.nanes=TRUE, row.nanes=TRUE, append=FALSE) om ae! Now. Lower ENTREPRISES GUY LARDINOIS SPRL. ussée de Courcelles, 79 + GOSSELIES we 1: O7VA.1655 - 34.1663 + fax: Oripesoas info@lardinois.com fon mrcony malas erpenies gude Cm JU Wo, Lo Meumabinl dt L LULL 38 Omm Mdwe OOO On Pour SOW Qu iy Oi qrrwwowmne NU. Louriptouguomenk Lt iresties os ontorgctennar ante tics 2 4 Ssmun < im(oestsotary ~ oesiektval + osteeoten + 0 3 Fg SUEY WB 0, Aad ren + 0, Maat 0, A ‘a summary (RLM)Scoefficients #get the coefficient estimates> RUNLE CI OlKchu tual Cotemnur sumnary(RUM)Scoetficients{yh) #get the model coefficient estinates fnodel-coef.estimates <- RIMgcoef # get the model coefficient estimates (use "coefficients" or "coef?) & Cuda Man UL d'afficher sumnary(RLM)$coefFicients[,2] #get the standard errors of the coefficient estimates Ly OGKCHA tia LCOE LYPLY Lolimis ‘#model.coef.se <- sqrt(diag(vcov(RLM))) # get the standard errors of the coefficient estimates, i.e., the square root of the diagonal elements in the variance-covariance matrix, onega) > hoe summary (RLM)$coefficients[,3] #get the t* or "t empirical value” ‘summary(RLM)$coefficients[,4} #get the p-values 6 Og P-VOLUL How to-conpute all. these elenents for Inktval? ste) | Ape nagcmn BLO # get the coefficient estinate for daktval ly _Ofeche -CLULELERM LUE 2.0. voLteLL OL Cau lens an “Amktval setrevetreotinateaiy =H -get-the coefficient estinatestorg frag p e-Inktval <- sumary(RLM)Scoefficients[2,2] # get the standard error ate For the coefficient of Inktval oes coef. se. Inktval <- nodel.coef.se(2] # get the standard error estinate for the coefficient of tnktval vt # calc ¢ statistic aul , Alcona. BERET value <- ee os(t_value_Inktval), ef-dot}t # Glcp Value for the t-ratio (cbuateray es bu sole aa tk RONDA 3 soveat pik to ane a eel er ae Cup UL clark unt DO. CL tun RLM <- 1m(DB$1salary ~ ex + cae ‘+ DB$ceoten) § ranean Beo,anr Ragy = 0,406 sof y=0881501ary AAS Fem c tamtty-n meancy yc cAI con dipend vr uty a. > SCE <- sum( (predict (RLM). = mean(y))92)g0,5 ible fe Ser sen sero el Cpu, Neo) ~ mony ry aE sum(resid(Rum)*2) QU. ees X sakes teas Reece stey ciegriy Dw. maggodiy 6 d0p rinse, sma) B re tous yours hd hve nachuchin UR dany tt ext bur saajusted Rsquared? GuurrumvOALy cle Lou pi n=length(y) dofeemnRnde > comme Le -oleque fudem ‘Ad|R=Sq====((n~2)/dOF)*(SCRISCT) a Library(ear) crn MULL Hig DELON LOL LLetL) bo. WOU CL C22 COL} = A ae LinearHypothesis(RLMT, ¢("DB$1sales=1",“DB$1mktval=1")) 3) ar LO. popu See oe So rots scat a tog, OL Ady - A ‘ow to compute the §* in a jolnt test step by step @ ae cotou Fe Nec conor ! Lu 2VOd 4xpi@ ae (pie oe CAL SLs fve cannot use the R'2 to compute the F* since the dependent 4s nat the Sone SIF the dependent variable had been the same, then we can use: No. fares AED OY crmspene Wer Caaf em Rerne PONE,
  • LUtLneL bent At’ LMAKLE car tLe foes st mL fond oe LOU, A NESICLULA CLL IMEC, COLULOLIUL ‘efee urine dur von. = Im(Fesiduals(RLM ®) ~ OBsceoten + DBSisales + DBFIaktval) 1. 'AL1 <> sunmary(RA_1)$r. squared > Cry VOL enue RY (RY Dae Let done meRsq RAT ee C pour un bom mn) i_crit <- qchisq(0.95,d1_num) #m in the LM-test is equal to q in the F-test rejet_UM <- ifelse(LMenp>chi_crit, 1,0) val <- pehisq(LM_emp, dl_nun, lower=FALSE) # calc p Value for the LM test om suyeite ie teat econses om chong de domunit Ss ‘#CSEXIa Om, utiuae br ce read. xsx(‘Magetsnlant aneettnden ot) RLM <- Im(b$wage ~ bSfemale) femot.) VoUoet BULOLLLL simmer(HlN) fe YOM cates te Shona i anata +4: Ys ct ‘hom x0 + 3,089 a,6na40 = ¥, 029 raya, RLM <= In(bSnage ~ bSFemale + bfeduc + bSexper + DStenure) summary(RLM) Y--4,63 - 4, Wika +0, S54 Kat WORKS +0) Aby scseac EERE Tat migany, at clk ofsuraLcar tn POLO Int educad}= beduc » mean(bfaduc) jut ON
      Om corr Lo aay summary(RLM) fy Q, Ff LiLeNUAW POLOUMAIAL puuenk nkuct Mh Maka omely Corea POV Nayont O. LO HSH Yo GIB =A 31K, +0,5PXa + 0,036 Xz + O AY, RIM <- In(bSluage ~ bffenale + bfeduc + bSexper + bexpersq + bétenure + eR : summary (RU POMEL. GALCLOLLOLLO WLLL, Om, pour ATU QUA COLL 40503 Qu Pmarment Go oun un %& em chonat de bose ‘pour tout le monde’ RLM <- In(bdSlvage ~ bésbelavg + béSabvavg + baSeduc + bdSexper + bdsexpersa + bdsblack) N= 0, 3A-0) Ay - O/O1dKa, +0; OB FAs +O) OWL Ky = 0; 0006 XS -0,ANX ‘summary(RLM) y 2 i omnes’ POM CEL UL BOM Uo LOM Qu M'ULOLLL Que bbdmee=subset (bdyefenaler=mo) Luv homumnuy (alin aus f-o = t=. erem clone LN <- In(odaSluage ~ bdnsbelavg + bdaSabvave + bdsfedut + binSexper + Mit) bdagexpersq + bdugblack) ae sor hhene snlun, 0. MEQ ALY Quam Jai: ¥- 0,6 -0,ABXq -034%a +0,058%s 40, ee OW X,, - 0,000iK, -0, 0X ROUX singlefem <- array to For (4 an 2:0) Tmonment fien dedouue ARDS HE narrledadsandstendists Wen Magth cmpormnens Mien dt LN <- In(bdS lage ~ bdvfbelavg + bdvbabvave + baWeduc + bikexper + pexpersq + bdw$black’ jo. AYU il { Aen. ‘summary (RLM) seal ea ! a estas om fpuend or bax ud) La Pur. pout. bw <> read. x1sx(*wagesxlsx"yssheetindex-=1) Ne ) Fmtoure a mb ce 2uqnt singlenale: <- roe 3) naremale <- array(ccWW, , ‘ . erat renee) | om cut b utes qrbcr od Lor fol (Na Ke rae Af (bw$married(i] == 0 && buffemale[i] == @) fe sigimlenitenn aad OM (uel cue BOUELL, } wom yénapu. tur {Hf arrdedet and Fenaleo then marmmalest; else marrmale-®; ecuLag te) arried[i] == 1 && bwsfenaie(] = f mrreetclit a Seer uf at GhaKvicue > Ain eplatememetee | EE qarriede and fetes then marrfenets else mies: tawata- cbt CONDE. AF (onsnarried{i] == 1 88 beSfenaie(i} == 2 ’ ercteti}es Mea fe Ps era + #if married0 and fenale=t then singfem-i; else singfeno; —Lt Qt | iF (bwSnarried{i] == @ && beéFemaleli) Voscheyrger.. | singlefen[i] <> 1 y EE bwSsinglenale < singlenale Quand LO boeke tae Pye bwémarrmale <- marrmale = CROLQUAL SUCALOUL O& EEL Ime LOW busmarcfen <- marrfen SpigejOn VO RUOU emi. Betinglete inlet array(@,c(N,1)) T3<- array(®,¢(N,1)) T4 <- array(@,¢(N,1)) for (4 in 1:N){ if (b2Smonth[i] mii] <1) if (b2Smonth i] Ti] <1) if (b2Snonth[ i] TSE] <1) Af (b2smonthti] vali] <1} = 4) : ao mine que basta <- TL vom your bagi <1 Covent mar Ovic ae AQLEW b2sT3 <- 13 basta <-14 #ETAPER n9=1m(b2SVENTES~ b2SPUB+b2ST1+b2$T2+b2$T3) sunmary(m9) ox i. chowgerment és b <- read. x1sx(*wagel-xisx"y"sheetIndex:="2) bSinteraction = b$fenale*b$married eg <-In(bsluage~ b$Fenalesb$narried+ bfinteraction+ bSeduct bSexper + nyreg <- hexpersq + bstenure + bStenursa) summary (nyreg) Cor cdomeonoupedianinoccdapuoumjau 8 1 m vx pluw puqne (fmote) Lam WELL OW | to. ceuilotien uri. 2d Te me Bort fOr AUP | éfoms, amas Une dey d (UL) ETAPE 1 bSinteraction = bSfenale*bgeduc " mee iL <-Im(b$1wage~ bSfenalerbseduct bSinteraction® bSexper + bfexpersq + béter & Jee de Aue + bstenursq) ‘on zg summary) OU OULULU@AC LO a dome s PON AWN. JU cle CLO. omoteulnk Audit ve ‘MINC<~1m(b$lwage~ b$female+b$educt bSinteraction+ b$exper + bSexpersq + oe AMCOLUL 3 + bstenursa) 3 <-ln(bslnage~ Wfeduce BBexper + bfexpersq + bStenure + bStenur Oe gerae 3 UE CL ur, Qh CNC UL Pe RLM <- In(bSlwage ~ bSfemale + bSeduc + tsp bSexpersq + bstenure + : g bStenursq) OM UU Dk samervtn quit’ funvod. “Lae “aba ee yoLabue un -b$educ- mez scot, ae a bseduca b$experadj=b$exper-mean(bsexper) AUCOLUE GU Noy, Dstenurendj-osterune-nean(ostenure) b$experadj2=bSexperadj*bSexperad QUOCAOLK UW iSienurand{aetstoarpipupomensy |e SOUL Cormpe. Gu CULO. m2 <-in(osivage ~ bSFenale+ bSeducads, eSexerady+ bSexperad;2+ bstenuread+ 3 bstenuread}2) ean ey femout : ssreooeney Ruquss LOU Om Pund Bus MALOU OAUstiLe oct? : m3 <-1m(b$lwage ~ b$female+ bSeducady ‘+p$interad} +b$experadj+ bexperadj2+ S vstenureadj+ pstenureadj2) _{! QO’ OL LO. OLA yuLrore® a Semoryi?) MU ChOUNQL Ny RUMLOW AUQML Le UEC? MEN momcony, 1 bcenror Quo manakivs AU LE apt Plum : “ACSEXS MUSHCLIVUS AR MARU pve tof e te dt QO. ont ETAPE 5. 4 MyoB <- ae ee Ak LO i ALM <~ Im(HyO@Srp ~ NyOBErFese summary (RLM) ” crangerrele jhe es Sook ayo AOMUE ap eeaesnte msc (eo Cae Que hae Janquesberareest(FESTACRUMD) | Gt 2:0, 0% oo Coa 50,05 ) clare : MOMNLOLIL scrext me bose A bh < read.xlse(thpricetsxlsx", sheetIndex = *hpricel”) View(bh) fu mom sronifioctie fi ene G. 7AAH4 4 0,000 Xn * 0 BBX By 35), ‘Summary (m1) bh$priceresideresid(mt) -2 a Aegouck Wu» nisidua pene esi Se facownt 6. to, evatar plest ce Brecon pagan = Aeympo 4 ETAPE 2 - Use log if you can (sonetines useful to get rid of 9) cron wes heal Tae SNcetncetcoerend antes, Stet fay 0- summary (22) “U purenontédo. hitenoredda.. ©) BL(Pvatens) ub unl yo pluie cd’ pikeorcetior @) bhsyhut<-Fitted(mt) bhSyhut2<-bhsyhut2 n3=1m(bi$priceresid2~bhsyhut+bhgyhut2) ssunmary(m3) U_enpiriquel=(suamary(n3)$4F[2]+sunnary(m3)Sdf[1])*summary(m3)$r.squared ULempiriquer gchisq(.95, df=sunmary(n3)$df(2)-1) ovale <=" L-pehisa(LALempiriqued,sumary(aa)saf[2)-2 ) p-value # ETAPE 3 - Nodéle en log: TW complet ind=In(bh$price-bh$1lotsizesbh$lsqrF+bhgbdrms) summary (m4) bhge=resid(n4) . bhge2 = bh$e"bhse bh$llotsizesq ~bhSllotsize"2 bhSlsqrftsq =bhSisqrét"2 bhsbdrmssq =bhsbdrns”2 bhginteri21-oh$Llotsize*bhsisarft bhSintert31-bh$1lotsize*bhsbdras bhfinter231=bh$1sqrFt*bhsbdras uSelm(bh$e2 ~ bh$llotsize +th$lsqrft +bhSbdrns +bh$Llotsizesq +bh$Isqrftsq ‘sbnSbdenssq +bhSinter12] sbh$inter13+bh$inter231) sunmary(2) LL enpi=(sunmary (a5) $dF[2]+surmary (n5)$4F[1])*sunmary(nS)$r-squared LLenpi ‘gchisq(.95, dfesunmary(x5)$4F[1]-1) pevalue <- 1-pehisq(LM_enpi, sunnary(n5)$0°[2]-1 ) p-value # ETAPE 4 - Modble en log: TW sinplifié ACTEXS (Run-CSEX4-if the-database."bw"-is-not available) (bw$1wage~beSmarrmalevbu$marrfemvbussinglefem +bufeduc +bwéexper ousexpersq +bxétenure sbwftenursq_), ? vod sumary(m) 23 CL ol Oe mam COL 2) Alec} om im poy mye botest(ma) dh bia prtk ob Given the p-value > 5%, we should not expect much ciurell On te ore Library (sandwich) AvcovHC = SE robust to heteroskedasticity const: no correction HCO: Defult/Basic sandwich estimator (Eicker/Huber/White). “Classic” White correction. HCI-HC3: Small sample improvements, described in Long and Ervin (2000) HCA: Improve small-sample performance, especially in the presence of influential observations, described in Cribari-Neto (2004) #The coeftest function runs the regression with robust SE ye de, i pr ACOUF ahr A tLe Comparison” dtp “a ON th t(sapply(c("const™, “HCO”, "HCI", "HC2", “HC3", "HC4"), Funetion(x) sart(diag(vcoviC(ml, type = x))))) Tou Lux COW NOBUSRS 4 OWS P-VOlULs PULUY Re eT NOTA BENE: Correcting for heteroskedasticity in joint hypotheses Testing whether elasticities are both equal to 1 (See in Lesson 4) # Run lesson 4 if the OB database is available RLMT <- Im(DaSisalary ~ Da$1sales + DBSInktval + Dagceoten) Library(car) LinearHypothesis(RLMT, ¢("DBSIsalé LinearHypothesis(RLNT, ¢("DB$1sali “chisa") test = “Chisq” implies the use of a Wald test ‘Correcting for heteroskedasticity and autorocorrelation in joint hypotheses for in times series is based on the use of vcovHAC and not vcovHC, see below) *, "DBSImktval=1")) "DBSImktval=1"), vcov=veovHe, test = #C7EXS OM CUAL bp <- read.x1sx(*mroz.x1sx", sheetIndex = "MROZ") View(bp) bp$nuifeincadjebp$nwifeinc- mean(bpsnwifeinc) bpSeducad; =bo$educ-nean(bp$educ) bpSexperadj=bp$exper-mean(bpSexper) beSexperadj2=bp$experad3*bpSexperadj bpSagead)=bp$age-nean(bpsage) bpSkids1tead}=bp$kidsits-mean(bpSkids1t6) bpBkidsgesad}-bpskidsges-mean(bpSkidsges) "eEDeIm(bp$inlF-bpsnwifeincad sbpSeducadj+bpSexperadj +opSexperadj2 +bpSagead) *bpSkidslt6ad} +opS$kidsgesad) sumnary(regp) bptest(regp) coeftest(negp, vcovHC) #"HC3" by default coeftest(negp, VcovHC(regp, type="HC8")) most frequent #UECON-B-=SERIAL CORRELATION, #CBEx1 - areusch-sodfrey MCW bax B <- read. x1sx(*Alphabet:xlsx" ysheetIndex="sheet2") View(B) B<-B[complete.cases(B),] reg=Im(B$RET~1) ~> Cry nieyume 208 nenclumunse ur ur ob ‘summary(reg) Library(Imtest) nlags:5 « {bay ga 8 ely (pasgepaaiemimaeemrasensties WR cool reg=1m(B$RET~B$RET_1) 1 cary (es) West neqne ur Sra con ten Library(imtest) AUMUND & FOL MOYEN LOL b= A mlags=5 a § kyon to bgtest(reg, order = nlags, type = "F%) ; ; bgtest(reg, order = nlags, type = "Chisq") COULLOL? ALU IN nugek Ja Aeitye CLUE Bon) forum. cb. puvisietun ous p CBEX2 & CBEX3E - Breusch-GodFrey + HACSE WRIEL- A WEG SVom, doe COU A P <- read. x1sx(“phillips.xlsx",.sheetIndex.=."phillips*) on Cup View(P) P<-Pl complete. cases(P),] Stow \ ; hom anter 20 AQNUr avec amis MMOULS, LLU LLU dunem=di ff (P$unem) dinates” |W COLL A PegsIm(P$dinf~P$dunem) 3. Cry) amryr®) Conn prone curtih chOroge tk Unplate f# Breusch-Codfrey Library(Imtest) bptest (reg) nlags=5 bgtest(reg, order = nlags, type = "Chisq") , OM Tuyen A’ hiypo clobinct OU COUR MOUS CarunL whacse On ML Vere NW? uctome 0m VO. LOL hur 2c OULE Cyr qu Mmavran 10. Library(sanarden) a dio trata #SE robust to heteroskedasticity AND autocorrelation hon coeftest(reg, vcov = vcovHAC) #Neweywest Nose # Neweykiest() (by default) uses a Bartlett kennel with nonparanetric bandwidth selection (Newey and West 1987, 1994). ##Other Options (Comparison) # kernHAC() and NeweyWest() both use prewhitening (by default). coeftest(reg, veov = kernHAC) # kernHAC() uses a quadratic spectral kernel with parametric bandwidth selection (Andrews 1991, Andrews and Monahan 1992). coeftest(reg, vcov = weave) # weave() implements the class of weighted empirical adaptive variance estimators (Lumley and Heagerty 1999).
  • You might also like