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 R code is:

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

Make sure to comment on your code using #.

Problem 1

From the set \(\{1.5, 15, 0, 54, 23\}\), pick two numbers and perform subtraction, multiplication, and square-root operations.

# Pick two numbers from the set
number_1 <- 15
number_2 <- 1.5

# Subtract the second number from the first number
number_1 - number_2
## [1] 13.5
# Multiply the two numbers
number_1 * number_2
## [1] 22.5
# Find the square root of each selected number
sqrt(number_1)
## [1] 3.872983
sqrt(number_2)
## [1] 1.224745

Problem 2

Suppose you have a set of numbers representing assignment scores:

# Create a vector containing the assignment scores
scores <- c(87, 100, 91, 95, 81.5, 0, 39, 74, 92)

# Calculate the average score and round it to two decimal places
average_score <- round(mean(scores), 2)
average_score
## [1] 73.28
# Find the maximum and minimum scores
maximum_score <- max(scores)
minimum_score <- min(scores)

maximum_score
## [1] 100
minimum_score
## [1] 0
# Count how many scores are above the average
scores_above_average <- sum(scores > mean(scores))
scores_above_average
## [1] 7
# Create new_scores using elements at indices 2 through 6
new_scores <- scores[2:6]
new_scores
## [1] 100.0  91.0  95.0  81.5   0.0

Problem 3

# Create a vector with the number 1 repeated 5 times and print it
repeated_ones <- rep(1, 5)
repeated_ones
## [1] 1 1 1 1 1
# Create a sequence from 1 to 10 with a step of 2 and print it
step_sequence <- seq(from = 1, to = 10, by = 2)
step_sequence
## [1] 1 3 5 7 9
# Repeat the sequence from 1 to 3 two times and print it
repeated_sequence <- rep(1:3, times = 2)
repeated_sequence
## [1] 1 2 3 1 2 3

Problem 4

# Create a vector containing several data types
mixed_vector <- c(1, "two", 3.0, TRUE, 2)

# Check the class of the vector
class(mixed_vector)
## [1] "character"
# Coerce the vector to numeric and print it
# "two" cannot be converted to a number, so it becomes NA
numeric_vector <- suppressWarnings(as.numeric(mixed_vector))
numeric_vector
## [1]  1 NA  3 NA  2