CREATING SEQUENCES OF NUMBER

Creating sequences of numbers

In our next section, it will be incredibly useful to know how to create sequences in order to define the steps of a loop. And since I haven’t really talked to you about how to do that yet, now seems like a good time to do it.

The sign “:” will create a sequence of numbers starting with the number on the left of the sign, by increment of 1, until the number on the right is reached (but not exceed)

Example:

1:10
[1]  1  2  3  4  5  6  7  8  9 10
5.5:20
[1]  5.5  6.5  7.5  8.5  9.5 10.5 11.5 12.5 13.5 14.5 15.5 16.5 17.5 18.5 19.5

Pretty easy, right?

If you want something with more precise control, you can use the function “seq()” that will give you a sequence of numbers between 2 specified values, and based either on a given step size (with the argument “by”), or by dividing the interval given by the two values in ‘n’ sections. The number of sections is given through the argument “length.out”  (or “length” for short).

seq(from = 1, to = 21, by =2)     # Creating a vector going from 1 to 21 by increment of 2
[1]  1  3  5  7  9 11 13 15 17 19 21
seq(1,21,by=2)                    # id. but shorter
[1]  1  3  5  7  9 11 13 15 17 19 21

seq(-1,1,length.out=10)           # Creating a vector going from -1 to 1 with a sequence length equal to 10.
[1] -1.0000000 -0.7777778 -0.5555556 -0.3333333 -0.1111111  0.1111111
[7]  0.3333333  0.5555556  0.7777778  1.0000000

Another useful feature is to be able to repeat values (or a set of values) a certain number of times. The function “rep()” allows you to repeat elements of a vector (numerical, factor or other) in two ways. First, you can repeat each individual element ‘n’ times. To do that, set the argument “each” to the desired number of repetitions.

vec=c(1,2,3)
rep(vec, each=4)
[1] 1 1 1 1 2 2 2 2 3 3 3 3

Or, you can repeat the whole vector ‘n’ times. To do that, set the argument “times” to the desired number of repetitions.

rep(vec, times=4)
[1] 1 2 3 1 2 3 1 2 3 1 2 3

INTRODUCTION

Let's look at one of R's most useful assets: functions, and how to write your own.

LET’S GET LOGICAL

Learn more about what's true, false, logical tests and how to use them.

CONCLUSION

And they lived happily ever after! The End!

FUNCTION, THE GENERAL STRUCTURE

Need your work to function? Know how functions work!

FUNCTION: IN THE LOOP

How to iterate, repeat, recur.