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
# this chunk was made by keyboard shortcut
Make sure to comment on your code using #
.Subtraction .Multiplication .square root
# subtraction
54-23
## [1] 31
#multiplication
1.5*15
## [1] 22.5
# Square root
sqrt(54)
## [1] 7.348469
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
average_score <- sum(scores)/9
round(average_score, 2)
## [1] 73.28
#Find the Maximum and Minimum score
max(scores)
## [1] 100
min(scores)
## [1] 0
#Find how many scores were above the average, use coding for this
avg <- mean(scores)
above_averagenum <- sum(scores > avg)
print(above_averagenum)
## [1] 7
#create a new set of scores, call it new_scores. The new list should include elements 2 to 6
new_scores <- scores[2:6]
print(new_scores)
## [1] 100.0 91.0 95.0 81.5 0.0
# Create a vector with the number 1 repeated 5 times. Print it
numberone <- c(1,1,1,1,1)
print(numberone)
## [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
sequence_oneto10 <- seq(1, 10, by = 2)
print(sequence_oneto10)
## [1] 1 3 5 7 9
# Create a vector by repeating a sequence from 1 to 3, 2 times. call it
rep <- rep(1:3 , time = 2)
# Create a vector with different class types
mixed_vector <- list(1, "two", 3.0, TRUE, 2)
# Check the class of the vector
check_classes <- lapply(mixed_vector, class)
print(check_classes)
## [[1]]
## [1] "numeric"
##
## [[2]]
## [1] "character"
##
## [[3]]
## [1] "numeric"
##
## [[4]]
## [1] "logical"
##
## [[5]]
## [1] "numeric"
## Coerce to numeric and print it
setnumeric <- sapply(mixed_vector, as.numeric)
## Warning in lapply(X = X, FUN = FUN, ...): NAs introduced by coercion
print(setnumeric)
## [1] 1 NA 3 1 2