9.3 Exercise 3. Character vector manipulation (10 minutes)

Create the script “exercise3.R” and save it to the “Rcourse/Module1” directory: you will save all the commands of exercise 3 in that script.
Remember you can comment the code using #.

1- Go to Rcourse/Module1 First check where you currently are with getwd(); then go to Rcourse/Module1 with setwd()

Answer
getwd()
setwd("Rcourse/Module1")
setwd("~/Rcourse/Module1")

2- Create vector w as:

w <- rep(x=c("miRNA", "mRNA"), times=c(3, 2))

3- View vector w in the console: how does function rep() work ?
Play with the times argument.

Answer
rep(x=c("miRNA", "mRNA"), times=c(3, 4))
## [1] "miRNA" "miRNA" "miRNA" "mRNA"  "mRNA"  "mRNA"  "mRNA"
rep(x=c("miRNA", "mRNA"), times=c(10, 2))
##  [1] "miRNA" "miRNA" "miRNA" "miRNA" "miRNA" "miRNA" "miRNA" "miRNA" "miRNA" "miRNA" "mRNA"  "mRNA"

4- What is the output of table(w) ? What does the table function do ?

5- Type w[grep(pattern=“mRNA,” x=w)] and w[w == “mRNA”]
Is there a difference between the two outputs?

Answer
w[grep(pattern="mRNA", w)]
## [1] "mRNA" "mRNA"
w[w == "mRNA"]
## [1] "mRNA" "mRNA"
# no difference between the outputs

6- Now type w[grep(pattern=“RNA,” w)] and w[w == “RNA”]
Is there a difference between the two outputs?

Answer
w[grep(pattern="RNA", w)]
## [1] "miRNA" "miRNA" "miRNA" "mRNA"  "mRNA"
w[w == "RNA"]
## character(0)
# grep outputs 5 values but == outputs none

What is the difference between == and grep ?

Answer

= looks for exact matches.
grep looks for patterns.

7- Create vector g as:

g <- c("hsa-let-7a", "hsa-mir-1", "CLC", "DKK1", "LPA")

How many elements do w and g contain?

Answer
length(w); length(g)
## [1] 5
## [1] 5

8- Name the elements of g using the elements of w.
(i.e. the names of each element of g will be the elements of w).

Answer
names(g) <- w