.Subtraction .Multiplication .square root
#simplest answer:
54-0 #subtraction
## [1] 54
23*15 #product
## [1] 345
sqrt(1.5) #sq root
## [1] 1.224745
Suppose you have a set of numbers representing the assignments scores:
scores <- c(87,100, 91, 95, 81.5, 0, 39, 74, 92)
#Calculate the average of the scores, and round your answer to two decimal number
round(mean(scores),2) # 2-decimal place rounded mean
## [1] 73.28
#Find the Maximum and Minimum score
max(scores) # maximum score
## [1] 100
min(scores) # minimum score
## [1] 0
#Find how many scores were above the average, use coding for this
#not covered in class yet but I've done this in previous programming courses
avg <- mean(scores)
above_avg <- 0 #initialize a loop with above_avg as a counter of scores that are greater than the average
for (element in scores) { #for-loop through the elements of scores
if (element > avg) {
above_avg <- above_avg + 1 #increment the counter when the score is greater than the average
}
}
print(above_avg) #print the number of scores greater than the average
## [1] 7
#more efficiently, using function calls:
print(sum(scores>avg)) # when doing the sum() of the logical evaluations, R automatically coerces the logical TRUEs to numerical 1s and FALSEs to 0s; thus the sum() adds the number of scores greater than the average. I found this useful approach when googling 'how to count number of elements equal to a value'.
## [1] 7
#another approach as learned in class is
print(length(scores[scores>avg])) # this creates a vector of scores greater than the average; the length() gives the number of elements of that vector
## [1] 7
#Create a new set called new_scores that includes the elements from indices 2 to 6 of the scores vector
new_scores <- c(scores[2:6]) #subset of elements 2 through 6
print (new_scores)
## [1] 100.0 91.0 95.0 81.5 0.0
Read section 2.3, then answer the following questions
# Create a vector with the number 1 repeated 5 times. Print it
fiveones <- rep(1, times=5) #repeat 1 five times
print(fiveones)
## [1] 1 1 1 1 1
# Create a vector with a sequence of numbers from 1 to 10 with a step of 2. Print it
onetotenby2 <- seq(from=1, to=10, by=2)
print(onetotenby2)
## [1] 1 3 5 7 9
# Create a vector by repeating a sequence from 1 to 3, 2 times. Print it.
oneto3twice <- rep(1:3, times=2)
print (oneto3twice)
## [1] 1 2 3 1 2 3
mixed_vector <- c(1, "two", 3.0, TRUE, 2)
# Check the class of the vector
class(mixed_vector)
## [1] "character"
## Coerce to numeric and print it
coerced_vector <- as.numeric(mixed_vector)
## Warning: NAs introduced by coercion
print (coerced_vector)
## [1] 1 NA 3 NA 2