Here you will find useful functions to create series of numbers to populate your tables and objects. These functions are also quite useful when you want to make a simulation or try functions on a random data set or on a test sample. Note that some functions return integers (numbers with no decimal) while other functions return numbers with (many) decimals.
X:Y
is used to create a series of numbers ranging from X to Y:
[code language=”r”]
series1 <- 4:12
series1
series2 <- 12:4
series2[/code]
seq(from= X, to= Y, by= Z)
is used to create a sequence of numbers ranging from X to Y by increments of Z:
[code language=”r”]
series1 <- seq(from= 2, to=18, by= 4)
series1
[/code]
runif(Y)
returns a series of Y random numbers between 0 and 1:
[code language=”r”]
series1 <- runif(1)
series1
series2 <- runif(5)
series2
[/code]
runif(Y, min=X, max=Z)
returns a series of Y random numbers ranging from X to Z:
[code language=”r”]
series1 <- runif(5, min=10, max=100)
series1
[/code]
floor(runif(Y, min=X, max=Z))
returns a series of Y random integers ranging from X to Z:
[code language=”r”]
series1 <- floor(runif(5, min=10, max=100))
series1
[/code]
NB: the function floor() rounds up the numbers by returning the largest integer not greater than the number to process.
sample(X, Y, replace=T/F)
returns a sample of Y integers taken in the vector X. replace
should be followed by either TRUE
or FALSE
. It defines whether or not the same data element can be chosen repeatedly in the sample.
[code language=”r”]
series1 <- sample(1:10, 5, TRUE)
series1
[/code]
An interesting property of the function sample()
is that it can be used to shuffle a vector, something which can be useful for randomization of data elements. Simply omit the argument Y. In the following example, sample()
has kept, shuffled and printed all values between 1 and 10:
[code language=”r”]
series2 <- 1:10
series2
sample(series2)
[/code]
rep(X, Y)
repeats X as many times as defined by Y. Note that rep(X, each=Y)
returns Y copies of the first item in X, then Y copies of the second item in X, then…
[code language=”r”]
series1 <- rep(5,3)
series1
series2 <- rep(1:5,3)
series2
series3 <- rep(1:5, each=3)
series3
[/code]