Regression Analysis - Exercise Class 1 - Solutions Katja Helena Andersen (email: katjan@sam.sdu.dk, office: V2-203c-2) 09-09-2025 Abstract In Lectures 1 and 2, you should have all gone through the following: • software installation • variables • operations • file organization • working directory • plotting • functions • loading data • packages • data structures • data frames • control flows The objective of this class will be to provide an introduction to the program R. Along the way, I will give some of my own personal tips when working with R. We conclude the class with a feedback session. I created this document using R Markdown and the ‘Knit to PDF’ function. You can learn more about it here: https://rmarkdown.rstudio.com. What is R? R is primarily a statistical software tool, but it is also a simple and accessible programming language. In this course you will only use the most basic functions, so do not let the word “programming” scare you. It requires almost no basic knowledge to understand the essential features of the program, and if you are willing to invest some time in using the program, it is certainly manageable. The RStudio Desktop program contains 4 different windows: 1. Workspace → Here you write a series of commands, formulas, loops, etc. in a R Script (.R) or R Markdown (.rmd) file. 2. Console → The workplace output is printed in this window. You can also type individual commands in the console, and access previously executed commands using the up arrow (↑) key. 3. Environment → Saves variables, models, arrays, vectors, matrices, etc. 4. Files, plots, packages, help, viewer. → All remaining tasks. 1 Start I like to start my file with clearing all the memory. # Clear all memory rm(list=ls()) # You can also delete individual objects using rm(object1, object2) # Clear unused memory gc() # It will never make you lose variables Then, I add any packages that I might need. #install.packages("package") #library(package) #install.packages("tinytex") library(tinytex) Vectors and Matrices Vectors are an ordered list of numbers or information. If they contain numeric values, they are very easy to work with in R, e.g. # Save vectors/variables x = c(1, 5, 10) y = c(2, 3, 4) z = c(-4, 1, 0.2) w = 1:10 q = seq(from = 1, to = 10, by = 2) Above, we have assigned the vectors to variables called x, y, z, w, and q. Subsequently, the vector can be called by typing the name of the variable. The vectors can also be used in formulas and for various calculations. # Test q ## [1] 1 3 5 7 9 # Calculate x+y ## [1] 3 8 14 x*y ## [1] 2 15 40 x%*%y 2 ## [,1] ## [1,] 57 You can also combine them to form matrices: Matrix.One = cbind(x,y,z) Matrix.Two = rbind(x,y,z) Matrix.One ## x y z ## [1,] 1 2 -4.0 ## [2,] 5 3 1.0 ## [3,] 10 4 0.2 You can take specific elements out of the matrix by defining [row, column] Matrix.One[1,3] ## z ## -4 You can name the columns and rows in these matrices using the colnames and rownames features. colnames(Matrix.One) = c("Column 1", "Column 2", "Column 3") rownames(Matrix.One) = c("x", "y", "z") Matrix.One ## Column 1 Column 2 Column 3 ## x 1 2 -4.0 ## y 5 3 1.0 ## z 10 4 0.2 Problem 1 (a) Construct the following elements: x <- c(1, 2, 3) y <- c(20, 20000, 15, 5) data <- c("Year", "Income", "Education", "Experience") z <- c(18, 30000, 14, 3) dataset <- rbind(y,z) colnames(dataset) <- data xˆ2 ## [1] 1 4 9 xˆ3 ## [1] 1 8 27 3 y ## [1] 20 20000 15 5 data ## [1] "Year" "Income" "Education" "Experience" dataset ## Year Income Education Experience ## y 20 20000 15 5 ## z 18 30000 14 3 Problem 1 (b) R is often used to work with very large datasets, so it is very important that you learn to handle these. There may be missing values, incorrect values, and other errors in your dataset. In most situations, descriptive statistics can help you better understand your data. If you create a separate folder for each exercise set, then all your files will be easier to manage. If your R documents are stored in the same folder as your data files, you can use the following procedure to load the data. 1. Click on Session at the top of the menu bar. 2. Go to Set Working Directory 3. Click on To Source File Location The Set Working Directory command will be executed and various functions can be used to load different data file types. For .raw files, the read.table command can be used. data <- read.table( "/Users/katjan/Documents/GitHub/regression-analysis/exercises/E01/airfare.raw", header = TRUE, na.strings = c(".", "NA", "na", "") ) #or you can specify which path like I did head(data) # Gives first few rows ## year origin destin id dist passen fare bmktshr ldist y98 y99 y00 ## 1 1997 AKRON, OH ATLANTA, GA 1 528 152 106 0.8386 6.269096 0 0 0 ## 2 1998 AKRON, OH ATLANTA, GA 1 528 265 106 0.8133 6.269096 1 0 0 ## 3 1999 AKRON, OH ATLANTA, GA 1 528 336 113 0.8262 6.269096 0 1 0 ## 4 2000 AKRON, OH ATLANTA, GA 1 528 298 123 0.8612 6.269096 0 0 1 ## 5 1997 AKRON, OH ORLANDO, FL 2 861 282 104 0.5798 6.758094 0 0 0 ## 6 1998 AKRON, OH ORLANDO, FL 2 861 178 105 0.5817 6.758094 1 0 0 ## lfare ldistsq concen lpassen ## 1 4.663439 39.30157 0.8386 5.023880 ## 2 4.663439 39.30157 0.8133 5.579730 4 ## 3 4.727388 39.30157 0.8262 5.817111 ## 4 4.812184 39.30157 0.8612 5.697093 ## 5 4.644391 45.67184 0.5798 5.641907 ## 6 4.653960 45.67184 0.5817 5.181784 # You can also adjust this for x number of rows head(data, x) # Or to give access to the whole dataset use View(data) # Order #data <- data[order(data$origin, data$year),] The following provide some descriptive statistics. summary(data$year) ## ## Min. 1st Qu. 1997 1998 Median 1998 Mean 3rd Qu. 1998 1999 Max. 2000 mean(data$fare) ## [1] 178.7968 sd(data$fare) ## [1] 74.88151 sd(data$fare) ## [1] 74.88151 cov(data$fare,data$ldist) ## [1] 28.72938 cor(data$fare,data$ldist) ## [1] 0.5819113 plot(data$dist,data$fare, main = "Correlation between distance and price", xlab = "Distance", ylab = "Price") abline(103,0.076, col="yellow") 5 300 100 200 Price 400 500 Correlation between distance and price 0 500 1000 1500 2000 2500 Distance The points to be used to make the line can be found using the following function: Reg1 = lm(data$fare ~ data$dist) Reg1 ## ## Call: ## lm(formula = data$fare ~ data$dist) ## ## Coefficients: ## (Intercept) data$dist ## 103.26137 0.07632 File Formats Throughout the course we will encounter data sets in different file formats. For example, the comma separated values (.csv) format can be loaded into R using the read.csv command if the . is used for a decimal and the comma (,) is used as the separator. In other cases, the , is used for a decimal and the semi-colon (;) is used as the separator. To see the difference, open the file airfare-comma.csv using the read.csv command: #I like this package for easy file referencing library(here) ## here() starts at /Users/katjan/Documents/GitHub/regression-analysis 6 #To make life easier exercise_dir <- "/Users/katjan/Documents/GitHub/regression-analysis/exercises/" data <- read.csv( file.path(exercise_dir, "E01", "airfare-comma.csv"), header = TRUE, dec = ".", sep = ",", na.strings = c(".", "NA", "na", "") ) head(data) ## year origin destin id dist passen fare bmktshr ldist y98 y99 y00 ## 1 1997 AKRON, OH ATLANTA, GA 1 528 152 106 0.8386 6.269096 0 0 0 ## 2 1998 AKRON, OH ATLANTA, GA 1 528 265 106 0.8133 6.269096 1 0 0 ## 3 1999 AKRON, OH ATLANTA, GA 1 528 336 113 0.8262 6.269096 0 1 0 ## 4 2000 AKRON, OH ATLANTA, GA 1 528 298 123 0.8612 6.269096 0 0 1 ## 5 1997 AKRON, OH ORLANDO, FL 2 861 282 104 0.5798 6.758094 0 0 0 ## 6 1998 AKRON, OH ORLANDO, FL 2 861 178 105 0.5817 6.758094 1 0 0 ## lfare ldistsq concen lpassen ## 1 4.663439 39.30157 0.8386 5.023880 ## 2 4.663439 39.30157 0.8133 5.579730 ## 3 4.727388 39.30157 0.8262 5.817111 ## 4 4.812184 39.30157 0.8612 5.697093 ## 5 4.644391 45.67184 0.5798 5.641907 ## 6 4.653960 45.67184 0.5817 5.181784 Now try loading the file airfare-semicolon.csv file using the read.csv command or the airfare-comma.csv file using the read.csv2 command without specifying the separator or decimal symbol. What goes wrong in each case? data <- read.csv( file.path(exercise_dir, "E01", "airfare-comma.csv"), header = TRUE, dec = ".", sep = ",", na.strings = c(".", "NA", "na", "") ) data <- read.csv2( file.path(exercise_dir, "E01", "airfare-comma.csv"), header = TRUE, na.strings = c(".", "NA", "na", "") ) If you’re unsure about what symbols are used in a particular file, you can first try to open it in a plain texteditor. It is good practice to always specify the decimal and separator symbols even if the arguments are optional. Problem 2 Use the data set airfare.raw to answer the following questions. Some of the questions may require that you either use the internet or ?function to solve them. Variable labels can be added as follows: 7 #install.packages("sjlabelled") library(sjlabelled) labs <- c( "Year", "Origin", "Destination", "ID", "Distance", "Passengers", "Fare", "Market share", "Ln(distance)", "year=1998", "year=1999", "year=2000", "Ln(fare)", "Ln(distance) squared", "Concentration", "Ln(passengers)" ) # `data` is whatever you hvae called the data frame data <- set_label(data, label = labs) 2.a How many observations are there? nrow(data) ## [1] 4596 2.b How many observations are there for 1998? sum(data$year==1998) ## [1] 1149 2.c What is the average fare? mean(data$fare) ## [1] 178.7968 2.d What is the average price for flights with over 200 passengers? Subset.Data <- subset(data, passen>200) mean(Subset.Data$fare) ## [1] 176.0701 2.e Find the standard deviation of the variables fare, passengers and distance. Make use of sd(data$"column name"). sd(data$fare) ## [1] 74.88151 sd(data$passen) ## [1] 812 8 sd(data$dist) ## [1] 611.8315 2.f Find the variance of fare, passengers and distance. var(data$fare) ## [1] 5607.241 var(data$passen) ## [1] 659343.9 var(data$dist) ## [1] 374337.8 2.g Find covariance and correlation between the fare and passengers. cov(data$fare,data$passen) ## [1] -8289.807 cor(data$fare,data$passen) ## [1] -0.136337 #lm(y ~ x, data = data) Regression=lm(data$fare~data$dist) Regression ## ## Call: ## lm(formula = data$fare ~ data$dist) ## ## Coefficients: ## (Intercept) data$dist ## 103.26137 0.07632 plot(data$dist,data$fare, main = "Correlation between distance and price", xlab = "Distance", ylab = "Price") abline(103.26137,0.07632, col="red") 9 300 100 200 Price 400 500 Correlation between distance and price 0 500 1000 1500 2000 2500 Distance Problem 3 Download and load the second dataset BWGHT.raw. Each observation represents a woman’s pregnancy and includes characteristics of the household, each parent, the infant, as well as the smoking behavior of the pregnant woman. R has limited ability to display variable labels. After reading in the data, install the following package: #install.packages("sjlabelled") library(sjlabelled) data1 <- read.table(file.path(exercise_dir, "E01", "BWGHT.raw"), header = TRUE, na.strings = c (".", "NA", "Na","")) Then, run the following code to add variable labels to the data: labs <- c( "Family income", "Cigarette tax rate", "Cigarette price per pack", "Birth weight (oz)", "Father's education", "Mother's education", "Parity", "Gender = Male", "Race = White", "Cigarettes per day", "Ln(birth weight)", "Birth weight (lbs)", "Packs per day", "Ln(family income)" ) 10 # Replace `data` with the name you gave your dataset data1 <- set_label(data1, label = labs) nrow(data1) ## [1] 1388 3.a How many white women are there and how many have smoked during pregnancy? Subset.Data2 = subset(data1, white== 1) # Number of white women nrow(Subset.Data2) ## [1] 1089 #The number of white women who smoked during pregnancy length(which(Subset.Data2$cigs > 0)) ## [1] 165 sum(Subset.Data2$cigs>0) ## [1] 165 3.b What is the average number of cigarettes smoked in a day by white women? mean(Subset.Data2$cigs) ## [1] 2.029385 3.c Among the white women who smoked during pregnancy, what was the average daily consumption? Compare with question 3.b. #Remember: subset 2 only consists of white women. Subset.Data3 = subset(Subset.Data2, cigs > 0) mean(Subset.Data3$cigs) ## [1] 13.39394 3.d Find the average value of fatheduc (Father’s education) in the sample. Why are only 1192 observations used to find this number? mean(data1$fatheduc, na.rm = TRUE) ## [1] 13.18624 11 length(which(data1$fatheduc>0)) ## [1] 1192 3.e Use only the observations of white women and summarize the variable birth weight (bwghtlbs). In addition, create a plot to study whether there is a relationship between birth weight and the number of cigarettes smoked by white women. summary(Subset.Data2$bwghtlbs) ## ## Min. 1st Qu. 2.188 6.812 Median 7.500 Mean 3rd Qu. 7.503 8.312 Max. 16.938 #Here we look at the relationship between the baby's weight and the number of cigarettes smoked by a whi Reg2 = lm(bwghtlbs~ cigs, data = Subset.Data2) Reg2 ## ## Call: ## lm(formula = bwghtlbs ~ cigs, data = Subset.Data2) ## ## Coefficients: ## (Intercept) cigs ## 7.58161 -0.03858 summary(Reg2) ## ## Call: ## lm(formula = bwghtlbs ~ cigs, data = Subset.Data2) ## ## Residuals: ## Min 1Q Median 3Q Max ## -5.3941 -0.7066 0.0434 0.7934 9.3559 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 7.581613 0.039381 192.520 < 2e-16 *** ## cigs -0.038575 0.006532 -5.906 4.68e-09 *** ## --## Signif. codes: 0 ’***’ 0.001 ’**’ 0.01 ’*’ 0.05 ’.’ 0.1 ’ ’ 1 ## ## Residual standard error: 1.224 on 1087 degrees of freedom ## Multiple R-squared: 0.03109, Adjusted R-squared: 0.0302 ## F-statistic: 34.88 on 1 and 1087 DF, p-value: 4.684e-09 plot(Subset.Data2$cigs, Subset.Data2$bwghtlbs, main = "Correlation between cigarettes and birth weight", xlab = "Number of Cigarettes", ylab = "Weight in Pounds") abline(Reg2, col = "red") 12 10 5 Weight in Pounds 15 Correlation between cigarettes and birth weight 0 10 20 30 40 Number of Cigarettes Saving Data If you want to save objects, use the following command: #save.image(here(Desktop/03_Teaching/Regression_Analysis/Ex01/Ex01.RData")) # for example You can then load it at a future date using the load command. Feedback • Classes will be primarily held in English, unless otherwise. • Exercise sets and solutions will be in English. • Every week, there will be a portion of exercises that have to be completed before coming to class, and I will then provide the solutions. • We will have a focus on having time to do the rest of the exercises, and we will go through the solutions at the end. If we have spare time, we can look at some articles :-) Sneak Peak If you are all interested, I could introduce some interesting studies that we could discuss in class if we have time. This could be a weekly article club. Here is one I find hilarious but also makes a good point on causal inference when effects are large. You can find the article here: https://pmc.ncbi.nlm.nih.gov/articles/ PMC300808/ 13
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )