Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R numbers from 1 to 100 [duplicate]

Tags:

r

Possible Duplicate:
How to generate a vector containing a numeric sequence?

In R, how can I get the list of numbers from 1 to 100? Other languages have a function 'range' to do this. R's range does something else entirely.

> range(1,100) [1]   1 100 
like image 423
Colonel Panic Avatar asked Jul 12 '12 14:07

Colonel Panic


People also ask

How do you repeat numbers in a sequence in R?

How do you Repeat a Sequence of Numbers in R? To repeat a sequence of numbers in R you can use the rep() function. For example, if you type rep(1:5, times=5) you will get a vector with the sequence 1 to 5 repeated 5 times.

How do I generate a list of numbers in R?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.

How do you find the range of values in R?

We can find the range by performing the difference between the minimum value in the vector and the maximum value in the given vector. We can find maximum value using max() function and minimum value by using min() function. Example: R.


2 Answers

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100)) 

gives

 -5 100 

Instead, look at the : operator to give sequences (with a step size of one):

1:100 

or you can use the seq function to have a bit more control. For example,

##Step size of 2 seq(1, 100, by=2) 

or

##length.out: desired length of the sequence seq(1, 100, length.out=5) 
like image 88
csgillespie Avatar answered Sep 18 '22 16:09

csgillespie


If you need the construct for a quick example to play with, use the : operator.

But if you are creating a vector/range of numbers dynamically, then use seq() instead.

Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.

In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,

seq(a, b, -1) 

will raise an error for a=2, b=6, because the coder expected a decreasing sequence.

like image 32
Soumendra Avatar answered Sep 18 '22 16:09

Soumendra