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 + II Mac: Command + Option +
Make sure to comment on your code using #
.Subtraction .Multiplication .square root
# I used -, *, and sqrt() to perform these operations.
15-1.5
## [1] 13.5
0*54
## [1] 0
sqrt(23)
## [1] 4.795832
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
# Answer: 73.28. I put the mean function as the argument in the round function.
round(mean(scores),2)
## [1] 73.28
#Find the Maximum and Minimum score
# Answer: max = 100, min = 0.
max(scores)
## [1] 100
min(scores)
## [1] 0
#Find how many scores were above the average, use coding for this
#Answer: 7. I summed the output of the logical operation finding which scores were greater than the mean.
sum(scores>(mean(scores)))
## [1] 7
#Create a new set called new_scores that includes the elements from indices 2 to 6 of the scores vector
#Answer:100.0 91.0 95.0 81.5 0.0. I created a new vector and extracted only elements 2-6 from the scores vector.
new_scores <- c(scores[2:6])
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
# Answer: 1 1 1 1 1. I used the rep function and set x = 1, times = 5.
my_vec1 <- rep(1, times = 5)
my_vec1
## [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
#Answer: 1 3 5 7 9. I used the seq function and set from = 1, to = 10, and by = 2.
my_vec2 <- seq(from = 1, to = 10, by = 2)
my_vec2
## [1] 1 3 5 7 9
# Create a vector by repeating a sequence from 1 to 3, 2 times. Print it.
#Answer: 1 2 3 1 2 3. I again used the rep function. This time I created a vector with the numbers 1 to 3 and set that vector as x in the rep function. I set times = 2.
my_seq <- 1:3
my_vec3 <- rep(my_seq, times=2)
my_vec3
## [1] 1 2 3 1 2 3
mixed_vector <- c(1, "two", 3.0, TRUE, 2)
# Check the class of the vector
#Answer: character. I used the class() function.
class(mixed_vector)
## [1] "character"
## Coerce to numeric and print it
#Answer: 1 NA 3 NA 2. I used the as.numeric() function.
num_vector <- as.numeric(mixed_vector)
## Warning: NAs introduced by coercion
num_vector
## [1] 1 NA 3 NA 2