R Functions for Special Vectors

There will be instances where you will want to create a vector that contains a repeated value or special sequence. The obvious option I do not recommend is to simply type out the sequence with c() such as x <- c(1,2,3). In this blog post, I am going to introduce some common functions that will make R programming much easier. The first method is not a function, but rather it takes advantage of R’s system for handling numbers. You can specify a vector of numbers counting by one by simply separating the lower and upper bounds by a colon. Note that the “#” allows us to write comments in R, so anything after the # will generally not be executed as code.

x <- 1:3 #This will create a vector containing numbers 1 through 5 counting by 1

print(x)

output: 1 2 3

If we want a sequence of numbers that counts by a different increment, we can use the seq() function for greater control. The seq() function takes 3 arguments you need to specify, the first is the lower bound, the second is the upper bound, and the third is what we are counting by. You can choose not to specify what we are counting by and specify length.out argument instead if you need a vector of a certain length. If you need a reminder of the arguments in a function, you can use the help() function to remember/learn what you can do.

help("seq") #This gives a short description of the seq function

x <- seq(1, 3, 0.5)

print(x)

output: 1.0 1.5 2.0 2.5 3.0

Now if you need to repeat the same value in a vector, you can use the rep() function. The rep() function is a little easier because it only takes two arguments. The first argument is what you want repeated and the second is how many times it should be repeated. Below I repeat the letter “a” 3 times.

x <- rep(“a”, 3)

print(x)

output: "a" "a" "a"

To wrap up, I want to mention that if you want a vector that contains the letters of the alphabet you can simply input “letters” as a variable in R to get all lowercase letters. Likewise, you can use “LETTERS” to get a vector of all uppercase letters. Admittedly, you will probably not often use the letters trick. However, you should find yourself using seq() and rep() frequently.

Previous
Previous

Using For Loops in R

Next
Next

Creating Variables in R