Extract Every nth Element of a Vector in R (Example)
On this page you’ll learn how to extract every nth element of a vector or column in the R programming language.
The content of the tutorial looks as follows:
- Creation of Example Data
- Example: Extracting Every 3rd Element of LETTERS in R
- Video & Further Resources
Let’s dive right in:
Creation of Example Data
As example data, we are simply using the LETTERS object, which is already provided by the basic installation of the R programming language:
LETTERS # "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"
Now, we will extract every nth element of this character vector…
Example: Extracting Every 3rd Element of LETTERS in R
In this example, we’ll extract every 3rd element of the LETTERS vector. For this task, we need to use a combination of the seq and length functions.
Have a look at the following R code:
LETTERS[seq(1, length(LETTERS), 3)] # "A" "D" "G" "J" "M" "P" "S" "V" "Y"
As you can see, the previous R syntax returned every 3rd letter of the alphabet.
Note that you could apply this R code to every other vector or even to columns and variables of data frames.
Video & Further Resources
If you need further information on the contents of this tutorial, I can recommend watching the following video of the Statistics Globe YouTube channel. In the video, I illustrate the R programming code of this article in a live programming session:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may want to have a look at some of the other articles on this website:
In this article you learned how to take a subset of every nth element from a vector in the R programming language. Note that we could use basically the same syntax to select every nth row of a data frame as well. If you have further questions, please let me know in the comments section.
Statistics Globe Newsletter