2 Pages

Section 9 R-code

Course: STATS 107, Spring 2012
School: Harvard
Rating:
 
 
 
 
 

Word Count: 513

Document Preview

f=file.choose() survey=read.csv(f,header=T) names(survey) t.test(text_day~gender, #1) var.equal = FALSE, data=survey) by(survey$text_day,survey$gender,mean,na.rm=T) by(survey$text_day,survey$gender,sd,na.rm=T) by(!is.na(survey$text_day),survey$gender,sum,na.rm=T) boxplot(text_day~gender,data=survey,col=c("red","blue"))...

Register Now

Unformatted Document Excerpt

Coursehero >> Massachusetts >> Harvard >> STATS 107

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
f=file.choose() survey=read.csv(f,header=T) names(survey) t.test(text_day~gender, #1) var.equal = FALSE, data=survey) by(survey$text_day,survey$gender,mean,na.rm=T) by(survey$text_day,survey$gender,sd,na.rm=T) by(!is.na(survey$text_day),survey$gender,sum,na.rm=T) boxplot(text_day~gender,data=survey,col=c("red","blue")) girls=survey$text_day[survey$gender=="female"] boys=survey$text_day[survey$gender=="male"] par(mfcol=c(2,1)) hist(boys,col="blue",breaks=50*c(0:24),xlim=c(0,1200)) hist(girls,col="red",breaks=50*c(0:24),xlim=c(0,1200)) set.seed(05242012) nsims=10000 diff.boot=rep(NA,nsims) girls=survey$text_day[survey$gender=="female" & !is.na(survey$text_day)] boys=survey$text_day[survey$gender=="male" & !is.na(survey$text_day)] for(i in 1:nsims){ girls.sample=sample(girls,length(girls),replace=T) boys.sample=sample(boys,length(boys),replace=T) diff.boot[i]=mean(girls.sample)-mean(boys.sample) } hist(diff.boot,col="slategray2") mean(diff.boot) sd(diff.boot) o=order(diff.boot) diff.boot.o=diff.boot[o] c(diff.boot.o[round(0.025*nsims)],diff.boot.o[round(0.975*nsims)]) t.star=qt(0.975,df=min(length(girls),length(boys))-1) c((mean(girls)-mean(boys))-t.star*sd(diff.boot),(mean(girls)-mean(boys))+t.star*sd(diff.boot)) 2*(1-sum(diff.boot>0)/nsims) #log.girls=log(girls+1) #log.boys=log(boys+1) #log.ci=c((mean(log.girls)-mean(log.boys))-t.star*sqrt(var(log.girls)/length(log.girls)+var(log.boys)/length(log.boys)),(mean(log.girls)-mean(log.boys))+t.star*sqrt(var(log.girls)/length(log.girls)+var(log.boys)/length(log.boys))) #exp(t.test(log.girls,log.boys)$conf.int) #exp(log.ci) #2) vs. L1 L2 vs. "L1.5" regression library(quantmod) library(quantreg) getSymbols("SPY", from = "2009-04-01", to = "2012-03-31",auto.assign = T) SPY.monthret=as.numeric(monthlyReturn(Ad(SPY))) getSymbols("AFL", from = "2009-04-01", to = "2012-03-31",auto.assign = T) AFL.monthret=as.numeric(monthlyReturn(Ad(AFL))) plot(AFL.monthret~SPY.monthret) #L1.5 L1.5.obj=function(beta,y,x){ b0=beta[1] b1=beta[2] return(sum(abs(y-b0-b1*x)^1.5)) } beta.hat=nlm(L1.5.obj,beta=c(0,1),y=AFL.monthret,x=SPY.monthret) beta.hat b1.hat=beta.hat$estimate[2] lm1=lm(AFL.monthret~SPY.monthret) rq1=rq(AFL.monthret~SPY.monthret) abline(lm1,col="red") abline(rq1,col="blue") abline(beta.hat$estimate,col="purple",lty=2) set.seed(05242012) nsims=10000 slope.boot=rep(NA,nsims) n=length(AFL.monthret) for(i in 1:nsims){ sample.indices=sample(1:n,n,replace=T) AFL.temp=AFL.monthret[sample.indices] SPY.temp=SPY.monthret[sample.indices] beta.hat.temp=nlm(L1.5.obj,c(0,1),y=AFL.temp,x=SPY.temp) slope.boot[i]=beta.hat.temp$estimate[2] } hist(slope.boot,col="slategray2") mean(slope.boot) sd(slope.boot) o=order(slope.boot) slope.boot.o=slope.boot[o] c(slope.boot.o[round(0.025*nsims)],slope.boot.o[round(0.975*nsims)]) slope.hat=beta.hat$estimate[2] t.star=qt(0.975,df=n-2) c(slope.hat-t.star*sd(slope.boot),slope.hat+t.star*sd(slope.boot))
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Harvard - STATS - 107
#1) Style Analysislibrary(quantmod)getSymbols("VWNDX",from="2009-01-01",to="2012-03-31")getSymbols("VDIGX",from="2009-01-01",to="2012-03-31")getSymbols("VHGEX",from="2009-01-01",to="2012-03-31")getSymbols("VITAX",from="2009-01-01",to="2012-03-31")VW
Harvard - STATS - 107
#Pairs Trading Companies:#Home Depot ("HD") and Lowes ("LOW")#Papa Johns ("PZZA") and Dominoes ("DPZ")#Walmart ("WMT") and Target ("TRGT")#McDonalds ("MCD") and Taco Bell/KFC/Pizza Hut ("YUM")#Dell ("DELL") and HP ("HPQ")#Coke ("COKE") and Pepsi ("
Harvard - STATS - 107
#1)library(quantmod)f=file.choose() #choosing a file that has the ticker namesthis one has 500 of them!crap=read.csv(f)tickers=as.character(crap[,1])getSymbols("SPY", from = "2009-03-01", to = "2012-02-29",auto.assign = T)SPY.monthret=monthlyReturn(
Harvard - STATS - 107
#1)#Monthly Returns over last 10+ yearslibrary(quantmod)getSymbols(tickers, from = "2002-01-01", to = "2012-02-01") stocks=list(IBM,MCD,KFT,F)means=100*apply(cbind(monthlyReturn(IBM),monthlyReturn(MCD),monthlyReturn(KFT),monthlyReturn(F),2,mean)sds
Harvard - STATS - 107
### Section 1 Code:# Playing with R and quantmod###R can do math:(10.5-12)/(5/sqrt(30)exp(2)sin(pi/6)#R has some built-in functions, that you can pass options (aka, parameters in a comp. sci. sense) to:log(10)log(10, base = 10)#You can store
Harvard - STATS - 107
Stat 107Section #10April 18 & 19, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-3pm, Thurs 2-3pm, Fri 1-3pm, Mon 2-3pm, Tues 2-3pm Required Lecture on Thursday (W
Harvard - STATS - 107
Stat 107Section #9April 11 & 12, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-3pm, Thurs 1-2pm, Fri 2-3pm Project Proposal: is due Thurs evening by 11:59pm. Plea
Harvard - STATS - 107
Stat 107Section #8April 4 & 5, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-3pm, Thurs 1-2pm, Fri 2-3pm, Tues (April 10): TBD Homework #5 is due Tuesday night by
Harvard - STATS - 107
Stat 107Section #7March 28 & 29, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-3pm, Thurs 1-2pm, Fri 2-3pm Homework #5 is due Tuesday, April 10, before midnight.
Harvard - STATS - 107
Stat 107Section #6March 21 & 22, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-3pm, Wed 3-5pm (this week only), Thurs 1-2pm, Fri 2-3pm Homework #4 is due Tuesday
Harvard - STATS - 107
Stat 107Section #5February 29 & March 1, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-3pm, Thurs 1-2pm, Fri 2-3pm Homework #3 is due Friday night before midnight
Harvard - STATS - 107
Stat 107Section #4February 22 & 23, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-3pm, Thurs 1-2pm, Fri 2-3pm Homework #3 is due next Friday night, Mar 2, before
Harvard - STATS - 107
Stat 107Section #3February 15 & 16, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-2:30pm, Thurs 1-1:30, Fri 2-3pm Homework #2 is due on Friday night, Feb 17th, be
Harvard - STATS - 107
Stat 107Section #2February 7-9, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Sections: Wed 1-2pm (SC-B10), Thurs 12-1pm (SC-216).Office Hours (SC-602): Wed 2-3pm, Fri 2-3pm Course website: my.harvard.edu/k85336. All section material will be
Harvard - STATS - 107
Stat 107Section #1February 1 & 2, 2012Logistics Kevin Rader, krader@hsph.harvard.edu. Office hours (SC-602): Wed 2-3pm, Fri 1-2pm (TBD in future) Course website: my.harvard.edu/k85336. All section material will be posted under 'Sections Kevin's Sect
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 25: Behavioral Finance and Wrap Up1Cognitive BiasesFundamental Limitations InHuman Mental ProcessesSimple Rules Of Thumb LeadingTo Faulty JudgmentsSimilar To Optical IllusionsPhysic
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 23: Technical Analysis1IntroductionTechnical analysis is the attempt to forecaststock prices on the basis of market-deriveddata.Technicians (also known as quantitativeanalysts or cha
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 22: A brief time on time series analysis1Time-Series Data and DependenceTime-series data are simply a collection ofobservations gathered over time.All the finance data weve looked at h
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 21: VaR and Resampling1Value at RiskSimply put, assume you have a $1,000,000portfolio (very cool! )You ask: What is the probability that I'd lose$X (OR MORE) over the next M months?M
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 19: Value at Risk1Playing with PerformanceAnalyticsSome R CodegetSymbols("AAPL",from="2009-01-01")getSymbols("JNJ",from="2009-01-01")getSymbols("SPY",from="2009-01-01")aaplret=monthl
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 18: Performance Analytics, part 21Style AnalyticsIs a forthcoming package in R that will allowone to do style analysis; in particular rollingstyle analysis.Recall, we assume the style
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 17: Performance Analytics, part 112Pairs Trading ReduxWe have you backtest a pairs tradingstrategy on this weeks homework.Based on an idea presented in a Brazilianpaperpaper on the
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 16: Pontificating about the Project and Beta1The Class ProjectImportant DatesApril 10th: project proposalMay 1st: project dueThere are least two directions one can takefor the final
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 15: Single Index Models, part 21Oh that Wayne.2Whats in the worksDear Prof. Parzen,I hope that you enjoyed the spring break. The IOP, Harvard Dems,Libertarians, and I have been talki
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 13: The Single Index Model1The World is Complicated2Systemic RiskFinancial Stability Board: a risk of disruption to financialservices that is caused by an impairment of all or parts o
Harvard - STATS - 107
STATE STREET ASSOCIATESOutlineSystemic risk:Applications for investors and policymakersThe absorption ratio as a measure of implied systemic riskThe absorption ratio and the pricing of risky assetsMark KritzmanWindham Capital ManagementMIT Sloan S
Harvard - STAT - 107
Stat 107: Introduction to Business and Financial StatisticsClass 10: Portfolios, part 31Recall: The Efficient FrontierMaximumReturn PortfolioExpected ReturnEfficient PortfoliosEfficientFrontierInefficient PortfoliosMinimum Variance PortfolioRi
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 9: Portfolios, part 21Return on a portfolioAssume we have n stocks of interestLet Ri be a random variable denoting thereturn of stockHence the return on a portfolio is given bytheth
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 6: Simulation (cont) andPortfolios, part 11Simulating Two AssetsIn the previous examples, we assumed wewere simply investing in one asset, themarket index.But that was purely for eas
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 4: Monte Carlo Simulation1Historical NoteThe name Monte Carlo simulation comesfrom the computer simulations performedduring the 1930s and 1940s to estimate theprobability that the cha
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 4: Statistics Review, Part II1As January goes so does the yearhttp:/blog.stocktradersalmanac.com/post/As-January-Goes-so-Goes-the-Year 2The Data3Review of Basic Statistics (cont)Rand
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 3: Statistics Review, Part I1Homework DiscussionDue Midnight Friday night via emailstat107spring2012@gmail.comIdea of Momentumpapers on websiteetfreplay.com200 day moving average (mo
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 2: Computing Discussion1What to ReadSomeone last time asked what web sites Iread. Too many is the short answer!But an interesting study was recentlyreleased that is good to look at ca
Harvard - STATS - 107
Stat 107: Introduction to Business and Financial StatisticsClass 1: Introduction1Where Am I?Michael Parzen: Sci 300bOffice Phone: 617-495-8711Google Voice: 617-942-0621Email: mparzen@stat.harvard.edu2Who Am I?3WarningThis is the first second(!
Texas San Antonio - BIO - 1404
Biology Notes 4/17/12From Gene to proteinTranscription&TranslationiClicker: Which of the following is the best example of gene expression?-mouse fur color resultsfrom pigment formed by gene encoded enzymesBacterial Cell:-Bacteria can simultaneously
Texas San Antonio - BIO - 1404
Biology Notes 4/19/12Regulation of gene expression-Bacterial Operons-Repressible tryptophan operon-Inducible lactose operon-Differential Gene Expression in EukaryotesBacterial Operon Modelprecursor->enzyme 1->enzyme 2->enzyme 3->tryptophanoperon-a
Texas San Antonio - SOC - 1013
Sociology Notes 4/16/12 Religion and SociologyWhat is religion? Set of beliefs adhered by the members of a community, incorporating symbols regarded with a sense of awe or wonder together with ritual practicesTheism A belief in on or more supernatura
Texas San Antonio - SOC - 1013
Sociology Notes 4/20Civil religion: Pledge of Allegiance U.S. Currency Oath of Office Oath in CourtScientology Aliens dropped into volcanoes in hawaii other religions are also crazy/all over the place hinduism, rebirth it will eventually become
Texas San Antonio - CHEM - 1122
Lab Final85-90% multiple choicemaybe some short answer2 hours!21 questions7 mathReview:hyrdate problemsnaming compounds p.61 from chemistry booklimiting reagent problembalance equation, convert all reactants to moles, use balanced equations, whi
Texas San Antonio - MAT - 1093
MAT 1093 Test 3 ReviewName_MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.Match the point in polar coordinates with either A, B, C, or D on the graph.1) 3,354BA321-5-4-3-2-112345
University of Texas - MS - 3053
First published in Exchange, the magazine of the Brigham Young University School of Business,the following twelve categories were developed to cover the root or cause of most ethicalbusiness dilemmas that one might encounter in their jobs. The following
University of Texas - SPN - 610
University of Texas - SPN - 610
University of Texas - SPN - 610
University of Texas - SPN - 610
University of Texas - SPN - 610
University of Texas - SPN - 610
University of Texas - SPN - 610
University of Texas - SPN - 610
University of Texas - ACC - 312
ACC 312 Fundamentals of Managerial AccountingMidterm Exam I, Spring 2012, Wednesday February 22nd 2012ACC 312 Fundamentals of Managerial AccountingMidterm Exam I, Spring 2012, Wednesday February 22nd 2012NameUTEID_InstructorClass Day_ TimeDO NOT
University of Texas - ACC - 312
University of Texas - ACC - 312
University of Texas - OM - 335
OM 335: Homework Assignment 11 SolutionsProblem 1:Home Depot is a large hardware store located in Long Beach Mall: The EverlastBinder, a special purpose glue is one of the items it sells. Each unit of EverlastBinder costs Home Depot $10. There is an a
UCSD - BILD - 1
Problem Set A1. If you know that Boron has an atomic number of 5 and an atomic mass of 11, what doyou know about the number of protons, electrons, and neutrons in its atoms?2. What is special about the outer electron shell, and what can you predict fro
UCSD - BILD - 1
1.a) What are the components of a phospholipid?b) How does each component affect the hydrophilicity or hydrophobicity of themolecule?c) Draw a simple picture of a phospholipid bilayer and indicate where thehydrophilic and hydrophobic regions are loca
UCSD - BILD - 1
1. Describe the experiment which demonstrated that proteins within the plasma membraneare able to move freely within the bilayer.2.a) How do the conditions inside a lysosome differ from those in the cytosol?b) How does the function of this organelle i
UCSD - BILD - 1
BILD 1 Problem Set D:1. Do enzymes make reactions more thermodynamically favorable (i.e. affect delta G)? Defend youranswer.2. How (specifically) does an enzyme catalyze a reaction?3. Draw the Free Energy and reaction progress graph for Exergonic and
UCSD - BILD - 1
BILD 1 Problem Set E1) Plant cells feature both mitochondria and chloroplasts. Indicate whether the following events occur duringPHOTOSYNTHESIS (P), RESPIRATION (R), or BOTH (B). Only one answer applies to each process.Hydrolysis of ATPOxidation of wa
UCSD - BILD - 1
BILD 1 Problem Set F:1) A gorilla has 48 chromosomes in its somatic cells. How many chromosomes did the gorilla inheritfrom each parent? How many chromosomes will be in the gametes of the gorilla? How manychromosomes will be in the somatic cells of the
UCSD - BILD - 1
Problem Set G, Winter 20111. What does the following pedigree tell you about the expressed trait? What are the genotypesof the first generation mother and father? What are the genotypes of their children? (hint, payattention to the genders).2. We now
UCSD - BILD - 1
Functional Groups andThermodynamicsBrian TsuiBILD 1 Review Session1/29/12OutlineThe 7 key functional groups in BILD 1CarbonylAminoSulfhydrylPhosphateHydroxylMethylThermodynamicsMetabolic PathwaysFunctional GroupsHydroxyl (Alcohols)Charact