7 Useful functions

Here we will learn a few more useful functions in R that will useful to us further along.

7.1 Sequences

[1] 1 2 3 4 5 6 7 8 9
[1] 1 2 3 4 5 6 7 8 9
[1] 1 3 5 7 9
[1] 0.0 1.5 3.0 4.5 6.0 7.5 9.0
 [1]  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0  5.5  6.0  6.5  7.0  7.5
[15]  8.0  8.5  9.0  9.5 10.0
 [1] 0 1 2 3 4 5 6 7 8 9

7.2 Repetitions

R also allows you to easily create vectors containing repetitions with the rep() function.

[1] "Isn't it time for a break?" "Isn't it time for a break?"
[1] 5 5 5
 [1] 1 2 3 4 5 1 2 3 4 5
 [1] 1 1 2 2 3 3 4 4 5 5
 [1]  4  3  2  1  0 -1 -2 -3 -4 -5  4  3  2  1  0 -1 -2 -3 -4 -5  4  3  2
[24]  1  0 -1 -2 -3 -4 -5  4  3  2  1  0 -1 -2 -3 -4 -5  4  3  2  1  0 -1
[47] -2 -3 -4 -5  4  3  2  1  0 -1 -2 -3 -4 -5  4  3  2  1  0 -1 -2 -3 -4
[70] -5  4  3  2  1  0
 [ reached getOption("max.print") -- omitted 25 entries ]
 [1]  1.000  1.375  1.750  2.125  2.500  2.875  3.250  3.625  4.000  4.375
[11]  4.750  5.125  5.500  5.875  6.250  6.625  7.000  7.375  7.750  8.125
[21]  8.500  8.875  9.250  9.625 10.000  1.000  1.375  1.750  2.125  2.500
[31]  2.875  3.250  3.625  4.000  4.375  4.750  5.125  5.500  5.875  6.250
[41]  6.625  7.000  7.375  7.750  8.125  8.500  8.875  9.250  9.625 10.000
[51]  1.000  1.375  1.750  2.125  2.500  2.875  3.250  3.625  4.000  4.375
[61]  4.750  5.125  5.500  5.875  6.250  6.625  7.000  7.375  7.750  8.125
[71]  8.500  8.875  9.250  9.625 10.000
 [ reached getOption("max.print") -- omitted 75 entries ]

7.3 Factors

Factors are variables in R which take on a limited number of different values, such variables are often referred to as categorical variables. For example in cross-national research, “Gender” is usually a variable that can either take “Male” or “Female” values. In R terms, the factor would be called Gender, and it would have two levels, “Male” or “Female”.

 [1] Male   Male   Male   Male   Male   Female Female Female Female Female
Levels: Female Male

Alternatively, we can use the gl() function, which generates factors by specifying the pattern of their levels. Where:

gl(n, k, length = n*k, labels = 1:n, ordered = FALSE)

  • n: number of levels
  • k: number of replications
  • length: length of the result. By default: length = n*k
  • labels: labels for the resulting factor levels
  • ordered: whether the result should be ordered or not
 [1] Male   Male   Male   Male   Male   Female Female Female Female Female
Levels: Male Female

Let’s try creating a factor of 3 colors

[1] Brown Red   Green
Levels: Brown Red Green
[1] Brown Brown Red   Red   Green Green Brown Brown Red  
Levels: Brown Red Green
 [1] Brown Red   Green Brown Red   Green Brown Red   Green Brown Red  
[12] Green
Levels: Brown Red Green
 [1] Brown  Red    Green  Yellow Brown  Red    Green  Yellow Brown  Red   
[11] Green  Yellow
Levels: Brown Red Green Yellow