Online Test Banks
Score higher
See Online Test Banks
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Create Vectors in R

To create a vector from a simple sequence of integers, for example, you use the colon operator (:) in R. The code 3:7 gives you a vector with the numbers 3 to 7, and 4:-3 creates a vector with the numbers 4 to –3, both in steps of 1.

To make bigger or smaller steps in a sequence, use the seq() function. This function’s by argument allows you to specify the amount by which the numbers should increase or decrease. For a vector with the numbers 4.5 to 2.5 in steps of 0.5, for example, you can use the following code:

> seq(from = 4.5, to = 2.5, by = -0.5)
[1] 4.5 4.0 3.5 3.0 2.5

Alternatively, you can specify the length of the sequence by using the argument length.out. R calculates the step size itself. You can make a vector of nine values going from –2.7 to 1.3 like this:

> seq(from = -2.7, to = 1.3, length.out = 9)
[1] -2.7 -2.2 -1.7 -1.2 -0.7 -0.2 0.3 0.8 1.3

You don’t have to write out the argument names if you give the values for the arguments in the correct order. The code seq(4.5, 2.5, - 0.5) does exactly the same things as seq(from = 4.5, to = 2.5, by = -0.5). If you use the argument length.out, you always have to be spell it out though.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

Inside Sweepstakes

Win an iPad Mini. Enter to win now!