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:

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 to watch 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.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

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. If you have further questions, please let me know in the comments section.

 

Subscribe to my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top