As it is suggested, before proceeding, please review Chapter 2 of An Introduction to R and the internal R Documentation for the seq() function (type ?seq in the R console).
1.2.1 Using the seq() function, generate the sequence 2, 5, 8, 11.
## seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)),
## length.out = NULL, along.with = NULL, ...)
seq(2,11,3)
## [1] 2 5 8 11
1.2.2 Use the seq() function to generate the sequence 9, 18, 27, 36, 45.
seq(from = 9, to = 45, by = 9)
## [1] 9 18 27 36 45
1.2.3 Generate the sequence 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 using the length.out parameter.
seq(9,90,length.out = 10)
## [1] 9 18 27 36 45 54 63 72 81 90
1.2.4 (For this exercise, first write down your answer, without using R. Then, check your answer using R.) What is the output for the code: seq(from = -10, to = 10, length.out = 5)
## There will be 5 numbers between -10 & 10.
seq(from = -10, to = 10, length.out = 5)
## [1] -10 -5 0 5 10
1.2.5 Assign value 5 to variable x. Write code 1:x-1 you should get 0, 1, 2, 3, 4. Write code 1 : (x-1) you will get 1, 2, 3, 4. Explain the discrepancy in the output.
## “:” has a higher evaluation priority than "-". So, first equation will creates seq 1:5 which is 1,2,3,4,5 and substracts 1 from each entity. The other equation generates a seq 1 to 4 which is 1,2,3,4.
1.2.6 (For this exercise, first write down your answer, without using R. Then, check your answer using R.) Create a vector a with values 1, 2, 3, 4. For the code seq(along.with = a), what will be the output?
a <- c(1,2,3,4)
seq(along.with = a)
## [1] 1 2 3 4
## creates a vector starting from 1. the length of the vector will be the lenth of a. So, if you change a to (5, 99999999, 123213, 433), the output will be still 1,2,3,4.
1.2.7 (For this exercise, first write down your answer, without using R. Then, check your answer using R.) Generate a sequence using this code: seq(from=1, to=4, by=1)
What other ways can you generate the same sequence?
#the output will be 1,2,3,4. Here are the options that will give the same output:
1:4
## [1] 1 2 3 4
seq(4)
## [1] 1 2 3 4
c(1,2,3,4)
## [1] 1 2 3 4
## all of the above will give the same output.
1.2.8 Generate a backward sequence from 5, 4, 3, 2, 1
## No matter if its a backward seq. The logic is the same. from..to..by. For "by" the default is 1.
5:1
## [1] 5 4 3 2 1
1.2.9 Assign x <- c(1, 2, 3, 4). Using the function rep(), create the below sequence
1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4
## rep() function replicates the values in x. rep(x, times)
x <- c(1, 2, 3, 4)
rep(x,3)
## [1] 1 2 3 4 1 2 3 4 1 2 3 4
1.2.10 Assign x <- c(1, 2, 3, 4) sing the rep() function generate the sequence:
1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4
## rep(x, each = n) replicates each number for n times
rep(x, each = 3)
## [1] 1 1 1 2 2 2 3 3 3 4 4 4