Exercise 2: Lesson 3

Q1. Let's use some functions.

a. Use sum() to add the numbers from 1 to 10.

Q1a: Solution
sum(1:10)
## [1] 55

b. Compute the base 10 logarithm of the elements in the following vector and save to an object called logvec: c(1:10).

Q1b: Solution
logvec<- log10(c(1:10))

c. Combine the following vectors and compute the mean.

a <- c(45, 67, 34, 82)
b <- c(90, 45, 62, 56, 54)
Q1c: Solution
mean(c(a,b))
## [1] 59.44444

d. What does the function identical() do? Use it to compare the following vectors.

c <- seq(2, 10, by=2)
d <- c(2, 4, 6, 8, 10)
Q1d: Solution
#tells us whether the two vectors are the same
identical(c, d)
## [1] TRUE

Q2. Vectors include data of a single type, so what happens if we mix different types? Use typeof() to check the data type of the following objects.

num_char <- c(1, 2, 3, "a")
num_logical <- c(1, 2, 3, TRUE, FALSE)
char_logical <- c("a", "b", "c", TRUE)
tricky <- c(1, 2, 3, "4")
Q2: Solution
#These were coerced into a single data type
typeof(num_char)
## [1] "character"
num_char
## [1] "1" "2" "3" "a"
typeof(num_logical)
## [1] "double"
num_logical
## [1] 1 2 3 1 0
typeof(char_logical)
## [1] "character"
char_logical
## [1] "a"    "b"    "c"    "TRUE"
typeof(tricky)
## [1] "character"
tricky
## [1] "1" "2" "3" "4"

(Question taken from https://carpentries-incubator.github.io/bioc-intro/23-starting-with-r.html)

Q3. fruit is a vector containing the common names of different types of fruit. Can you replace "kiwi" with "mango".

fruit<-c("apples", "bananas", "oranges", "grapes","kiwi","kumquat")  
Q3: Solution
fruit[5] <- "mango"
fruit
## [1] "apples"  "bananas" "oranges" "grapes"  "mango"   "kumquat"

Q4. Given the following R code, return all values less than 678 in the vector "Total_subjects".

Total_subjects <- c(23, 4, 679, 3427, 12, 890, 654)
Q4: Solution
Total_subjects[Total_subjects < 678]
## [1]  23   4  12 654

Q5. This question uses the vectors created in Q2. Using indexing, create a new vector named combined that contains:

The 2nd and 3rd value of num_char.
The last value of char_logical.
The 1st value of tricky.

combined contains data of what type?

Q5: Solution
combined <- c(num_char[2:3], char_logical[length(char_logical)],
              tricky[1])
typeof(combined)  
## [1] "character"
combined
## [1] "2"    "3"    "TRUE" "1"