STAT120 - Statistical Computing in R

Homework 2

Part I

  1. Suppose the following are the final high school GPAs of a group of college students: 3.62, 3.84, 3.95, 4.00, 3.12, 2.86, 3.77, 2.53, 3.26, and 2.90. Create a vector that stores these values in the order specified. Choose a variable name that’s descriptive but relatively short.
Show solution
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
gpa <- c(3.62, 3.84, 3.95, 4.00, 3.12, 2.86, 3.77, 2.53, 3.26, 2.90)
  1. For the vector you created in problem 1, print out which value is greater than 3.5 (i.e., the output should be: 1, 2,3,4,7)
Show solution
which(gpa>3.5)
[1] 1 2 3 4 7
  1. Use R to check how many students are recorded in the data set, what the maximum GPA is, and which student has the maximum GPA.
Show solution
length(gpa)
[1] 10
max(gpa)
[1] 4
which(gpa==max(gpa))
[1] 4
  1. Find the average GPA for this group of students.
Show solution
mean(gpa)
[1] 3.385
  1. Suppose the following are the SAT quantitative scores for the same group of students: 640, 680, 790, 730, 580, 560, 670, 450, 650, and 490, respectively. Create another vector that stores these SAT scores in the order provided. Double check that it has the right length.
Show solution
sat_quant <- c(640, 680, 790, 730, 580, 560, 670, 450, 650, 490)
length(sat_quant)
[1] 10
  1. Print out the SAT quantitative scores for the 2nd and 3rd students.
Show solution
sat_quant[c(2,3)]
[1] 680 790
  1. Print out the SAT quantitative scores for the students whose GPA is above 3.5. Avoid hard-coding: do not manually type 1, 2, 3, 4, 7 anywhere in your code.
Show solution
sat_quant[gpa>3.5]
[1] 640 680 790 730 670
  1. Create a vector for gender with the following values (in this order): 1, 1, 1, 0, 0, 0, 0, 0, 1, 1. Note that 1 represents “male” and 0 represents “female.” Double check that it has the right length.
Show solution
gender <- c(rep(1, 3), rep(0, 5), rep(1, 2))
length(gender)
[1] 10
  1. Find the average of the values in the gender vector you created in problem 8. Note that this represents the proportion of males in the group. Whenever you have 0/1 data (and only when this is true!), the mean is the proportion of 1’s.
Show solution
mean(gender)
[1] 0.5
  1. The respective years of the 10 students are: Senior, Freshman, Sophomore, Freshman, Junior, Sophomore, Sophomore, Freshman, Freshman, Senior. Create a factor vector that stores the year of students (hint: create a character vector first and convert it to factor). Use R to double check that its type is factor.
Show solution
year <- c("Senior", "Freshman", "Sophomore", "Freshman", "Junior", "Sophomore", "Sophomore", "Freshman", "Freshman", "Senior")
year <- as.factor(year)
class(year)
[1] "factor"
  1. Use the tapply function to print out the average GPA of students by Year. Your output should look like this.
Show solution
library(tidyverse)
gpa <- c(3.62, 3.84, 3.95, 4.00, 3.12, 2.86, 3.77, 2.53, 3.26, 2.90)
year <- c("Senior", "Freshman", "Sophomore", "Freshman", "Junior", "Sophomore", "Sophomore", "Freshman", "Freshman", "Senior")
year <- as.factor(year)
tapply(gpa,year,mean)
 Freshman    Junior    Senior Sophomore 
 3.407500  3.120000  3.260000  3.526667 
  1. Store the vectors you created previously (gpa, sat_quant, gender, and year) in a data frame using the data.frame() function. Then, use the group_by() function in tidyverse to get the average GPA of students by year.
Show solution
df.student <- data.frame(gpa,year,sat_quant,gender)
df.student %>% 
  group_by(year) %>%
  summarise(mean(gpa))
# A tibble: 4 × 2
  year      `mean(gpa)`
  <fct>           <dbl>
1 Freshman         3.41
2 Junior           3.12
3 Senior           3.26
4 Sophomore        3.53

Part II

  1. The dataset used in this part is salaries-by-college-type-clean.csv. Download the data and import it into R. Print the names of the variables.
Show solution
df.sal <- read.csv('../../../dataset/salaries-by-college-type-clean.csv')
str(df.sal)
'data.frame':   269 obs. of  8 variables:
 $ School.Name                      : chr  "Massachusetts Institute of Technology (MIT)" "California Institute of Technology (CIT)" "Harvey Mudd College" "Polytechnic University of New York, Brooklyn" ...
 $ School.Type                      : chr  "Engineering" "Engineering" "Engineering" "Engineering" ...
 $ Starting.Median.Salary           : num  72200 75500 71800 62400 62200 61000 61800 61100 58300 58100 ...
 $ Mid.Career.Median.Salary         : num  126000 123000 122000 114000 114000 114000 111000 110000 106000 106000 ...
 $ Mid.Career.10th.Percentile.Salary: num  76800 NA NA 66800 NA 80000 63300 71600 67200 62200 ...
 $ Mid.Career.25th.Percentile.Salary: num  99200 104000 96000 94300 80200 91200 80100 85500 85200 87900 ...
 $ Mid.Career.75th.Percentile.Salary: num  168000 161000 180000 143000 142000 137000 150000 140000 137000 142000 ...
 $ Mid.Career.90th.Percentile.Salary: num  220000 NA NA 190000 NA 180000 209000 182000 183000 201000 ...
  1. Print the names of the 3rd, 4th, and 10th school.
Show solution
df.sal$School.Name[c(3,4,10)]
[1] "Harvey Mudd College"                         
[2] "Polytechnic University of New York, Brooklyn"
[3] "Colorado School of Mines"                    
  1. Print all the information of the 3rd, 4th, and 10th school.
Show solution
df.sal[c(3,4,10),]
                                    School.Name School.Type
3                           Harvey Mudd College Engineering
4  Polytechnic University of New York, Brooklyn Engineering
10                     Colorado School of Mines Engineering
   Starting.Median.Salary Mid.Career.Median.Salary
3                   71800                   122000
4                   62400                   114000
10                  58100                   106000
   Mid.Career.10th.Percentile.Salary Mid.Career.25th.Percentile.Salary
3                                 NA                             96000
4                              66800                             94300
10                             62200                             87900
   Mid.Career.75th.Percentile.Salary Mid.Career.90th.Percentile.Salary
3                             180000                                NA
4                             143000                            190000
10                            142000                            201000
  1. Calculate the average Starting.Median.Salary of the first 20 schools.
Show solution
mean(df.sal$Starting.Median.Salary[1:20])
[1] 58750
  1. Print out all information of the school with the highest Starting.Median.Salary?
Show solution
df.sal[which.max(df.sal$Starting.Median.Salary),]
                               School.Name School.Type Starting.Median.Salary
2 California Institute of Technology (CIT) Engineering                  75500
  Mid.Career.Median.Salary Mid.Career.10th.Percentile.Salary
2                   123000                                NA
  Mid.Career.25th.Percentile.Salary Mid.Career.75th.Percentile.Salary
2                            104000                            161000
  Mid.Career.90th.Percentile.Salary
2                                NA
df.sal[which.min(df.sal$Starting.Median.Salary),]
                  School.Name School.Type Starting.Median.Salary
264 Morehead State University       State                  34800
    Mid.Career.Median.Salary Mid.Career.10th.Percentile.Salary
264                    60600                             34300
    Mid.Career.25th.Percentile.Salary Mid.Career.75th.Percentile.Salary
264                             46500                             72000
    Mid.Career.90th.Percentile.Salary
264                             91300
  1. Print out the names of schools with a Starting.Median.Salary of 65,000 or greater.
Show solution
myindex <- which(df.sal$Starting.Median.Salary >= 65000)
df.sal$School.Name[myindex]
[1] "Massachusetts Institute of Technology (MIT)"
[2] "California Institute of Technology (CIT)"   
[3] "Harvey Mudd College"                        
[4] "Princeton University"                       
  1. Print out the names of schools with a Starting.Median.Salary of 65,000 or greater OR with a Mid.Career.Median.Salary of 130,000 or greater (hint: to do something like Condition 1 OR Condition 2, the code is Condition 1 | Condition 2).
Show solution
myindex <- which(df.sal$Starting.Median.Salary >= 65000 | df.sal$Mid.Career.Median.Salary >= 130000)
df.sal$School.Name[myindex]
[1] "Massachusetts Institute of Technology (MIT)"
[2] "California Institute of Technology (CIT)"   
[3] "Harvey Mudd College"                        
[4] "Dartmouth College"                          
[5] "Princeton University"                       
  1. Print out the names of schools with a Starting.Median.Salary of 65,000 or greater AND with a Mid.Career.Median.Salary of 130,000 or greater.
Show solution
myindex <- which(df.sal$Starting.Median.Salary >= 65000 & df.sal$Mid.Career.Median.Salary >= 130000)
df.sal$School.Name[myindex]
[1] "Princeton University"
  1. Print out the names of schools with a Starting.Median.Salary between 55,000 and 60,000 (hint: you cannot write code like \(4<x<5\) in R. You need to separately write \(x>4\) and \(x<5\)).
Show solution
myindex <- which(df.sal$Starting.Median.Salary >= 55000 & df.sal$Starting.Median.Salary <= 60000)
df.sal$School.Name[myindex]
 [1] "Georgia Institute of Technology"          
 [2] "Colorado School of Mines"                 
 [3] "Illinois Institute of Technology (IIT)"   
 [4] "South Dakota School of Mines & Technology"
 [5] "Dartmouth College"                        
 [6] "Yale University"                          
 [7] "Brown University"                         
 [8] "Columbia University"                      
 [9] "University of California, Berkeley"       
[10] "Cal Poly San Luis Obispo"                 
[11] "University of Missouri - Rolla (UMR)"     
  1. Print out the names of ‘Party’ or ‘Engineering’ schools.
Show solution
df.sal$School.Name[df.sal$School.Type %in% c('Party','Engineering')]
 [1] "Massachusetts Institute of Technology (MIT)"                        
 [2] "California Institute of Technology (CIT)"                           
 [3] "Harvey Mudd College"                                                
 [4] "Polytechnic University of New York, Brooklyn"                       
 [5] "Cooper Union"                                                       
 [6] "Worcester Polytechnic Institute (WPI)"                              
 [7] "Carnegie Mellon University (CMU)"                                   
 [8] "Rensselaer Polytechnic Institute (RPI)"                             
 [9] "Georgia Institute of Technology"                                    
[10] "Colorado School of Mines"                                           
[11] "Stevens Institute of Technology"                                    
[12] "Illinois Institute of Technology (IIT)"                             
[13] "Wentworth Institute of Technology"                                  
[14] "Virginia Polytechnic Institute and State University (Virginia Tech)"
[15] "South Dakota School of Mines & Technology"                          
[16] "New Mexico Institute of Mining and Technology (New Mexico Tech)"    
[17] "Rochester Institute of Technology (RIT)"                            
[18] "Embry-Riddle Aeronautical University (ERAU)"                        
[19] "Tennessee Technological University"                                 
[20] "University of Illinois at Urbana-Champaign (UIUC)"                  
[21] "University of Maryland, College Park"                               
[22] "University of California, Santa Barbara (UCSB)"                     
[23] "University of Texas (UT) - Austin"                                  
[24] "State University of New York (SUNY) at Albany"                      
[25] "University of Florida (UF)"                                         
[26] "Louisiana State University (LSU)"                                   
[27] "University of Georgia (UGA)"                                        
[28] "Pennsylvania State University (PSU)"                                
[29] "Arizona State University (ASU)"                                     
[30] "Indiana University (IU), Bloomington"                               
[31] "University of Iowa (UI)"                                            
[32] "Randolph-Macon College"                                             
[33] "University of Alabama, Tuscaloosa"                                  
[34] "University of Mississippi"                                          
[35] "University of New Hampshire (UNH)"                                  
[36] "West Virginia University (WVU)"                                     
[37] "University of Tennessee"                                            
[38] "Ohio University"                                                    
[39] "Florida State University (FSU)"                                     
  1. Print out the average Starting.Median.Salary and the average Mid.Career.Median.Salary by different school types. Sort the output by the average starting median salary.
Show solution
df.sal %>%
  group_by(School.Type) %>%
  summarise(start=mean(Starting.Median.Salary), mid=mean(Mid.Career.Median.Salary)) %>%
  arrange(start)
# A tibble: 5 × 3
  School.Type   start     mid
  <chr>         <dbl>   <dbl>
1 State        44126.  78567.
2 Party        45715   84685 
3 Liberal Arts 45747.  89379.
4 Engineering  59058. 103842.
5 Ivy League   60475  120125