You are on page 1of 3

A Using knitR (R + LTEX) in R Studio: A Demo

Pairach Piboonrungroj1,2,
1. Logistics Systems Dynamics Group, Cardiff Business School, Cardiff University, United Kingdom 2. Chiang Mai School of Economics, Chiang Mai University, Thailand Email: me@pairach.com

1. Show only R source code 1 + 1 2. Show only output ## [1] 2 3. Show both source code and output 1 + 1 ## [1] 2 4. Show source code in grey shade but the output 1 + 1 [1] 2 5. Now, testing a linear model # x # e # y generating value for x variable from 1 to 100 <- c(1:100) creat error term <- rnorm(100, mean = 5, sd = 10000) computing y equal to 3 plus five times x plus random number = 10 + 100 * x + e

Set the format of all object called pdf() my_pdf = function(file, width, height) { pdf(file, width = 5, height = 5, pointsize = 10) } 6. See the scatter plot plot(x, y)

30000 0

10000

10000

30000

20

40 x

60

80

100

7. Lets build a linear model by regressing y on x # creating a linear model by regressing y on x as 'lm1' object lm1 <- lm(y x) # calling a summary of linear model result summary(lm1) ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## Call: lm(formula = y x) Residuals: Min 1Q Median -27498 -5830 -323

3Q 6265

Max 24228

Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -3457.7 2027.2 -1.71 0.09124 . x 132.8 34.9 3.81 0.00024 *** --Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Residual standard error: 10100 on 98 degrees of freedom Multiple R-squared: 0.129,Adjusted R-squared: 0.12 F-statistic: 14.5 on 1 and 98 DF, p-value: 0.000242

8. Now we can create a post-hoc plots to check assumptions of regression # Creating post-hoc plot for lm1 par(mfrow = c(2, 2)) plot(lm1)

Standardized residuals

Residuals vs Fitted
20000
98

Normal QQ
1 2 3
98

Residuals

30000

2000

4000 Fitted values

8000

46

46 2

2 1

Theoretical Quantiles

Standardized residuals

Standardized residuals

ScaleLocation
1.5
2 46 98

Residuals vs Leverage
3
98 7

1.0

0.5

0.0

Cook's distance 0.00 0.02 Leverage

2000

4000 Fitted values

8000

0.04