Professional Documents
Culture Documents
R (I)
Fall 2022
R and RStudio
▶ Console
▶ Code Editor
▶ Environment: what RStudio has loaded in memory
▶ Bottom right
▶ Files: working directory
▶ Plot: can save plot
▶ Packages: what packages have been installed, what packages
have been loaded in memory
▶ Help
Interface
▶ Query
▶ getwd()
▶ Change your working directory
▶ “Session” =>
▶ “Set Working Directory”
▶ “To Source File Loaction”: set to be the same as the opened
script
▶ “To File Pane Location”
▶ setwd("~/Desktop/R Files")
Getting Help
▶ help()
▶ Help on packages
▶ help(plot)
▶ Help on dataset
▶ help(cars)
▶ Search through R documentation
▶ ??plot
▶ Examples:
▶ example("lm")
Objects
▶ Types of variables
▶ Numeric
▶ Integer
▶ Character
▶ Factor
▶ Logical
▶ Create objects
Indexing
▶ a[2] <- 8
▶ a[1:2]
▶ a[c(1,2)]
▶ a[c(TRUE, TRUE, FALSE)]
Dataframe
▶ Install
▶ “Packages” => “Install”
▶ install.packages("foreign")
▶ Load
▶ check the box in front of package name
▶ library(foreign)
▶ Update packages: install again
Importing Data
▶ Menu:
▶ “File” => “Import Dataset”
▶ “Environment” => “Import Datase”
▶ Code:
▶ data sets in loaded packages:
▶ data(cars)
▶ csv:
▶ dfname <- read.csv("filename.csv")
▶ Excel:
▶ library(readxl)
▶ dfname <- read_excel("filename", sheet = "Sheetname")
▶ If not use first row as vairalbe name:
dfnanme <- read_excel("filename", sheet = "Sheetname",
col_names = FALSE)
▶ dta:
▶ packages “foreign” / “readstata13” depending on Stata version
▶ dfname <- read.dta("filename.dta")
▶ dfname <- read.dta13("filename.dta")
Removing Objects
▶ One-sample t-test
▶ t.test(auto$price)
▶ t.test(auto$price-6000)
▶ Two-sample t-test: difference in means between two groups
▶ t.test(Variable ~ GroupVar, data=dfname, var.equal=FALSE)
▶ Default: allowing unequal variances(var.equal = FALSE)
▶ Paired t-test
▶ t.test(bpbefore, bpafter, paired=TRUE)
▶ t.test(bpbefore - bpafter)
Plot
▶ plot(x, y)
▶ Common arguments
▶ type: type of plot desired
▶ "p" for points
▶ "l" for lines
▶ "b" for both points and lines
▶ xlab, ylab: labels for the x, y axes
▶ main: title for the plot
▶ sub: subtitle for the plot
▶ xlim, ylim
▶ Add straight line to a plot:
▶ abline(intercept, slope)
▶ abline(0,1)
Linear Regression
Specifications
▶ Basic
▶ lm(y~x1+x2+x3, data=dfname)
▶ Without constant
▶ lm(y~ -1+x1+x2+x3, data=dfname)
▶ Include squared term
▶ lm(y~x1+I(x1^2)+x2+x3, data=dfname)
▶ Incude interaction term
▶ lm(y~x1*x2+x3, data=dfname)
▶ lm(y~x1:x2+x3, data=dfname)
▶ Incude dummies
▶ lm(y~factor(x1)+x2+x3, data=dfname)
Linear Regression
Robust or Clustered Standard Errors
▶ sandwich, lmtest
▶ Heteroscedasticity-robust
▶ coeftest(model10,vcovHC)
▶ Cluster-robust
▶ coeftest(model10,vcovCL,cluster=auto$foreign)
Linear Regression
F-Test
▶ Package “car”
▶ linearHypothesis(model10,"mpg=0",type=c("F"))
▶ linearHypothesis(model10,c("mpg=0","weight=0"),type=c("F"))
Missing Values