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

54-23
## [1] 31
1.5*54
## [1] 81
sqrt(15)
## [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 decimals
avg <- round(mean(scores), 2)
print(avg)
## [1] 73.28
# find the maximum and minimum scores
max(scores)
## [1] 100
min(scores)
## [1] 0
# find how many scores were above the average
scores[scores > avg]
## [1]  87.0 100.0  91.0  95.0  81.5  74.0  92.0
# create a new set, new_scores, that includes the elements from indices 2–6 of the scores vector
new_scores <- scores[2:6]

Problem 3:

Read section 2.3, then answer the following questions.

# create a vector with the number "1" repeated 5 times. print it.
v1 <- c(1, 1, 1, 1, 1)
print(v1)
## [1] 1 1 1 1 1
# create a vector with a sequence of numbers from 1–10 with a step of 2. print it.
v2 <- c(1, 3, 5, 7, 9)
print(v2)
## [1] 1 3 5 7 9
# create a vector by repeating a sequence from 1–3, 2 times. print it.
v3 <- c(1, 2, 3, 1, 2, 3)
print(v3)
## [1] 1 2 3 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 
print(as.numeric(mixed_vector))
## Warning in print(as.numeric(mixed_vector)): NAs introduced by coercion
## [1]  1 NA  3 NA  2