R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

R Bridge Week 01 Quiz Page 1

Week 1 Quiz

This ungraded Week 1 quiz is intended as a hands-on-lab to help you build your skills working with R data types

and control structures. Solutions to all problems are immediately available, but you’ll learn the material more

durably if you attempt each problem before consulting its solution.

  1. Create a vector that contains 20 numbers. (You may choose whatever numbers you like, but make sure there are some duplicates.)
numVec <- c(1:8,7:14,7:10)
numVec
##  [1]  1  2  3  4  5  6  7  8  7  8  9 10 11 12 13 14  7  8  9 10
  1. Use R to convert the vector from question 1 into a character vector.
charVec <- as.character(numVec)
charVec
##  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "7"  "8"  "9"  "10" "11" "12"
## [15] "13" "14" "7"  "8"  "9"  "10"
  1. Use R to convert the vector from question 1 into a vector of factors.
numFactors <- as.factor(numVec)
numFactors
##  [1] 1  2  3  4  5  6  7  8  7  8  9  10 11 12 13 14 7  8  9  10
## Levels: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  1. Use R to show how many levels the vector in the previous question has.
nlevels(numFactors)
## [1] 14
  1. Use R to create a vector that takes the vector from question 1 and performs on it the formula 3????????2 ??? 4???
numVec <- 3 * numVec ^ 2 - 4 * numVec + 1
numVec
##  [1]   0   5  16  33  56  85 120 161 120 161 208 261 320 385 456 533 120
## [18] 161 208 261

??????? + 1. 6. Create a named list. That is, create a list with several elements that are each able to be referenced by name.

namedlist <- list(rank = 1:5, players = c("Ada Lovelace", "Grace Hopper"))

namedlist$players[2]
## [1] "Grace Hopper"
  1. Create a data frame with four columns - one each character, factor (with three levels), numeric, and date.
title <- as.character(c("Unforgiven","The Deer Hunter", "It Happened One Night",
             "The Bridge on the River Kwai", "Lawrence of Arabia",
             "The Silence of the Lambs", "The Godfather Part II", "Casablanca",
             "The Godfather", "All about Eve"))
genre <- c("Western", "Drama", "Comedy",
             "Drama", "Drama", "Drama", "Drama", "Drama", "Drama", "Drama")
wins <- as.numeric(c(4, 8, 5, 7, 7, 5, 6, 3, 3, 6))
release <- as.Date(c("1992-1-1", "1978-1-1", "1934-1-1", "1957-1-1", "1962-1-1",
          "1991-1-1", "1974-1-1", "1943-1-1", "1972-1-1", "1950-1-1"))

df <- data.frame(title, genre, wins, release)
df$title <- as.character(df$title)
str(df)
## 'data.frame':    10 obs. of  4 variables:
##  $ title  : chr  "Unforgiven" "The Deer Hunter" "It Happened One Night" "The Bridge on the River Kwai" ...
##  $ genre  : Factor w/ 3 levels "Comedy","Drama",..: 3 2 1 2 2 2 2 2 2 2
##  $ wins   : num  4 8 5 7 7 5 6 3 3 6
##  $ release: Date, format: "1992-01-01" "1978-01-01" ...

Your data frame should have at least 10 observations (rows). 8. Illustrate how to add a row with a value for the factor column that isn’t already in the list of levels. (Note: You do not need to accomplish this with a single line of code.)

dfnew <- data.frame(title="West Side Story", genre="Musical", 
                  wins=10, release="1961-1-1")
str(dfnew)
## 'data.frame':    1 obs. of  4 variables:
##  $ title  : Factor w/ 1 level "West Side Story": 1
##  $ genre  : Factor w/ 1 level "Musical": 1
##  $ wins   : num 10
##  $ release: Factor w/ 1 level "1961-1-1": 1
dfnew$release <- as.Date(dfnew$release)
dfnew$title <- as.character(dfnew$title)

str(dfnew)
## 'data.frame':    1 obs. of  4 variables:
##  $ title  : chr "West Side Story"
##  $ genre  : Factor w/ 1 level "Musical": 1
##  $ wins   : num 10
##  $ release: Date, format: "1961-01-01"
dfnew$title
## [1] "West Side Story"
str(dfnew)
## 'data.frame':    1 obs. of  4 variables:
##  $ title  : chr "West Side Story"
##  $ genre  : Factor w/ 1 level "Musical": 1
##  $ wins   : num 10
##  $ release: Date, format: "1961-01-01"
df <- rbind(df, dfnew)
df
##                           title   genre wins    release
## 1                    Unforgiven Western    4 1992-01-01
## 2               The Deer Hunter   Drama    8 1978-01-01
## 3         It Happened One Night  Comedy    5 1934-01-01
## 4  The Bridge on the River Kwai   Drama    7 1957-01-01
## 5            Lawrence of Arabia   Drama    7 1962-01-01
## 6      The Silence of the Lambs   Drama    5 1991-01-01
## 7         The Godfather Part II   Drama    6 1974-01-01
## 8                    Casablanca   Drama    3 1943-01-01
## 9                 The Godfather   Drama    3 1972-01-01
## 10                All about Eve   Drama    6 1950-01-01
## 11              West Side Story Musical   10 1961-01-01
str(df)
## 'data.frame':    11 obs. of  4 variables:
##  $ title  : chr  "Unforgiven" "The Deer Hunter" "It Happened One Night" "The Bridge on the River Kwai" ...
##  $ genre  : Factor w/ 4 levels "Comedy","Drama",..: 3 2 1 2 2 2 2 2 2 2 ...
##  $ wins   : num  4 8 5 7 7 5 6 3 3 6 ...
##  $ release: Date, format: "1992-01-01" "1978-01-01" ...
  1. Show the code that would read in a CSV file called temperatures.csv from the current working directory.
getwd()
## [1] "C:/Smriti_Cuny"
df <- read.table(file = "temperatures.csv", header = TRUE, sep = ",")
tail(df)
##          City Temp
## 1 Pittsburgh    36
## 2     Boston    30
## 3    Atlanta    55
## 4 New Jersey    31
str(df)
## 'data.frame':    4 obs. of  2 variables:
##  $ City: Factor w/ 4 levels "Atlanta ","Boston ",..: 4 2 1 3
##  $ Temp: int  36 30 55 31
# alternative:
df <- read.csv(file = "temperatures.csv")
df
##          City Temp
## 1 Pittsburgh    36
## 2     Boston    30
## 3    Atlanta    55
## 4 New Jersey    31
  1. Use a loop to calculate the final balance, rounded to the nearest cent, in an account that earns 3.24% interest compounded monthly after six years if the original balance is $1,500.
principal <- 1500
annual_interest_rate <- 0.0324 
compounding_periods_per_year <- 12
years <- 6

# loop below is less efficient than if we pre-calculated compounding_periods_per_year * years
#   and annual_interest_rate / compounding_periods_per_year
for (period in 1:(compounding_periods_per_year*years))
{
  principal <- principal + (principal * annual_interest_rate / compounding_periods_per_year)
}
print (principal)  # prints 1821.396
## [1] 1821.396
sprintf("%.2f", principal) #formats as 1821.40
## [1] "1821.40"
# alternative: calculating interest without a loop
principal <- principal * ( 1 + (annual_interest_rate/compounding_periods_per_year)) ^ 
  (compounding_periods_per_year * years)
print (principal)
## [1] 2211.655
  1. Create a numeric vector of length 20 and then write code to calculate the sum of every third element of the vector you have created.
nvect <- 1:20
print (nvect)  # check by hand: should sum to 63
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
nvect %% 3
##  [1] 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2
nvect %% 3 == 0
##  [1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE
## [12]  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE
sum(nvect)
## [1] 210
sum(nvect[nvect %% 3 == 0])   # answer; prints 63
## [1] 63
# alternative solution
nvect <- c(1:20)
sum(nvect[seq(0,length(nvect),3)])
## [1] 63
  1. Use a for loop to calculate ??? ???????? 10 ???????? ????????=1 for the value ???????? = 2.
x <- 2
sum <- 0
for (i in 1:10)
{
  sum <- sum + x ^ i
}
print (sum)
## [1] 2046
  1. Use a while loop to accomplish the same task as in the previous exercise.
x <- 2
sum <- 0
i <- 1
while (i <= 10)
{
  sum <- sum + x ^ i
  i <- i + 1
}
print (sum)
## [1] 2046
  1. Solve the problem from the previous two exercises without using a loop.
x <- 2
print(sum(x^(1:10)))
## [1] 2046