Create Vector with Intervals in R (2 Examples)
In this article you’ll learn how to create a vector containing numeric intervals in the R programming language.
Table of contents:
If you want to know more about these contents, keep reading.
Example 1: Creating Vector with Intervals Using seq() Function
In this example, I’ll show how to create a vector consisting of numeric intervals using the seq function in R.
Have a look at the R code below:
x1 <- seq(from = 100, # Applying seq function to = 200, by = 10) x1 # Print vector with intervals # 100 110 120 130 140 150 160 170 180 190 200
As you can see based on the previous output of the RStudio console, we have created a numeric vector ranging from 100 to 200 with intervals of 10.
Example 2: Extracting Every nth Element from Vector Using seq() Function
This example shows how to use the seq function to extract vector elements based on a specific interval.
For this example, we’ll use the LETTERS object, which is already provided by the basic installation of the R programming language:
LETTERS # Print LETTERS object # "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"
Let’s assume that we want to extract every fifth element of this LETTERS vector. Then, we can apply the following R code:
x2 <- LETTERS[seq(from = 1, # Subset using seq function to = length(LETTERS), by = 5)] x2 # Print subset of LETTERS # "A" "F" "K" "P" "U" "Z"
Looks good!
Video & Further Resources
Do you need further explanations on the R programming codes of the present article? Then you could have a look at the following video which I have published on my YouTube channel. I illustrate the R code of this page in the video:
Furthermore, you may read the other articles on my website. I have released numerous related tutorials already.
- How to Create a Vector of Zeros
- How to Create a Vector of Zero Length
- Create Comma Separated Vector in R
- R Programming Language
In this article you learned how to create a vector with intervals in the R programming language. If you have any further questions and/or comments, please let me know in the comments section below. Besides that, please subscribe to my email newsletter to receive updates on the newest articles.