R Basics

You can insert an R code chunk into an R Markdown document by using a keyboard shortcut. The default keyboard shortcut to insert an R code is:

Windows/Linux: Ctrl + Alt + I Mac: Command + Option + I

Make sure to comment on your code using #

Problem 1:

  1. From set = {1.5, 15, 0, 54, 23}, pick two numbers and perform the Following Operations:

.Subtraction .Multiplication .square root

set <- c(1.5, 15, 0, 54, 23)

x <- set[1]
y <- set[2]
#subtraction
print(x-y)
## [1] -13.5
#multiplication
print(x*y)
## [1] 22.5
#square root
print(sqrt(x))
## [1] 1.224745
print(sqrt(y))
## [1] 3.872983

Problem 2

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
print(mean(scores))
## [1] 73.27778
#Find the Maximum and Minimum score
print(max(scores))
## [1] 100
print(min(scores))
## [1] 0
#Find how many scores were above the average, use coding for this
x<-mean(scores) #placing the average of scores within a variable (x)
scores[scores>x]
## [1]  87.0 100.0  91.0  95.0  81.5  74.0  92.0
print(scores[scores>x])
## [1]  87.0 100.0  91.0  95.0  81.5  74.0  92.0
#Create a new set called new_scores that includes the elements from indices 2 to 6 of the scores vector

new_scores <- scores[2:6]
print(new_scores)
## [1] 100.0  91.0  95.0  81.5   0.0

Problem 3:

Read section 2.3, then answer the following questions

# Create a vector with the number 1 repeated 5 times. Print it
numOne <-c(1)
rep(print(numOne),5)
## [1] 1
## [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
twoStep <- seq(0,10, by = 2)
print(twoStep) 
## [1]  0  2  4  6  8 10
# Create a vector by repeating a sequence from 1 to 3, 2 times. Print it.
threeRepeatVector <- seq(0, 3, by = 1)
print(rep(threeRepeatVector, 2))
## [1] 0 1 2 3 0 1 2 3

Problem 4

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 

as_numeric_NA <- as.numeric(mixed_vector)
## Warning: NAs introduced by coercion
mixed_vector[2] <- as.numeric(mixed_vector)
## Warning: NAs introduced by coercion
## Warning in mixed_vector[2] <- as.numeric(mixed_vector): number of items to
## replace is not a multiple of replacement length
mixed_vector[4] <- as.numeric(mixed_vector)
## Warning: NAs introduced by coercion
## Warning in mixed_vector[4] <- as.numeric(mixed_vector): number of items to
## replace is not a multiple of replacement length
print(mixed_vector)
## [1] "1" "1" "3" "1" "2"
print(as_numeric_NA)
## [1]  1 NA  3 NA  2