Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

How to sequence in r?

5 Answer(s) Available
Answer # 1 #

In this lesson, you’ll learn how to create sequences of numbers in R. Sequences of numbers are used in many different tasks, from plotting the axes of graphs to generating simulated data.

The simplest way to create a sequence of numbers in R is by using the : operator. Type 1:20 to see how it works.

That gave us every integer between (and including) 1 and 20 (an integer is a positive or negative counting number, including 0).

We could also use it to create a sequence of real numbers (a real number is a positive, negative, or 0 with an infinite or finite sequence of digits after the decimal place). For example, try typing pi:10.

The result is a vector of real numbers starting with pi (3.142…) and increasing in increments of 1. The upper limit of 10 is never reached, since the next number in our sequence would be greater than 10.

Note also that pi is one of the few constants built in to R. Type ?pi to check the others.

What happens if we do 15:1? Give it a try to find out.

It counted backwards in increments of 1! This is sometimes useful for plotting coefficients from models in reverse order.

Remember that if you have questions about a particular R function, you can access its documentation with a question mark followed by the function name: ?function_name_here. However, in the case of an operator like the colon used above, you must enclose the symbol in backticks like this: ?:. (NOTE: The backtick (`) key is generally located in the top left corner of a keyboard, above the Tab key. If you don’t have a backtick key, you can use regular quotes.)

Pull up the documentation for : now.

Often, we’ll desire more control over a sequence we’re creating than what the : operator gives us. The seq() function serves this purpose.

The most basic use of seq() does exactly the same thing as the : operator. Try seq(1, 20) to see this.

This gives us the same output as 1:20. Check the help file for seq().

The help files show the arguments listed for the seq() function. The first two arguments are “from =” and “to =”. In R, you do not have to specify the arguments by name if you write out their values in the same order as written in the function. However, for complex functions it is often best practice to do so and makes your code much clearer.

For example, seq(from = 1, to = 20) will give the same output as seq(1, 20). Try it!

OK, let’s say that instead of 1 to 20, we want a vector of numbers ranging from 0 to 10, incremented by 0.5. seq(0, 10, by = 0.5) does just that. Try it out.

Or maybe we don’t care what the increment is and we just want a sequence of 30 numbers between 5 and 10. seq(5, 10, length = 30) does the trick. Give it a shot now and store the result in a new variable called my_seq.

If you look closely again at the help file for ?seq, you will not see an argument “length =”, but only “length.out =”. You can actually use any abbreviation of the argument name, as long as it is different from any other argument. You could even use just “l =”!

To confirm that my_seq has length 30, we can use the length() function. Try it now. To do this, you need to include the object ‘my_seq’ as the value of argument ‘x’ of length().

Let’s pretend we don’t know the length of my_seq, but we want to generate a sequence of integers from 1 to N, where N represents the length of the my_seq vector. In other words, we want a new vector (1, 2, 3, …) that is the same length as my_seq.

There are several ways we could do this. One possibility is to combine the : operator and the length() function like this: 1:length(my_seq). Give that a try.

Another option is to use seq(along.with = my_seq). Give that a try.

However, as is the case with many common tasks, R has a separate built-in function for this purpose called seq_along(). Type seq_along(my_seq) to see it in action.

There are often several approaches to solving the same problem, particularly in R. Simple approaches that involve less typing are generally best. It’s also important for your code to be readable, so that you and others can figure out what’s going on without too much hassle.

If R has a built-in function for a particular task, it’s likely that function is highly optimized for that purpose and is your best option. One of the philosophies of R (and Unix more generally) is to have tools (or functions) that do specific things very well and then link these together, rather than a single multi-purpose tool that does many things poorly.

This approach is like having a seperate knife, fork, and spoon, rather than a Spork … In most situations, cutlery (“silverware”) is superior to the Spork.

As you become a more advanced R programmer, you will learn how to link and nest these apparently simple functions to do incredibly powerful tasks. You will also design your own functions to perform tasks when there are no better options. We’ll explore writing your own functions in future lessons.

OK, back to the show. One more function related to creating sequences of numbers is rep(), which stands for ‘replicate’. Let’s look at a few uses.

If we’re interested in creating a vector that contains 40 zeros, we can use rep(0, times = 40). Try it out.

If instead we want our vector to contain 10 repetitions of the vector (0, 1, 2), we can do rep(c(0, 1, 2), times = 10). Go ahead.

Finally, let’s say that rather than repeating the vector (0, 1, 2) over and over again, we want our vector to contain 10 zeros, then 10 ones, then 10 twos. We can do this with the each argument. Try rep(c(0, 1, 2), each = 10).

Congratulations! Now you have several powerful tools that you can use to generate sequences of numbers. You also learnt to use the function length() and the ‘:’ operator. Your R skills are building!

Please submit the log of this lesson to Google Forms so that Simon may evaluate your progress.

[5]
Edit
Query
Report
Pier Tugend
Flagman
Answer # 2 #

In this lesson, you’ll learn how to create sequences of numbers in R. Sequences of numbers are used in many different tasks, from plotting the axes of graphs to generating simulated data.

The simplest way to create a sequence of numbers in R is by using the : operator. Type 1:20 to see how it works.

That gave us every integer between (and including) 1 and 20 (an integer is a positive or negative counting number, including 0).

We could also use it to create a sequence of real numbers (a real number is a positive, negative, or 0 with an infinite or finite sequence of digits after the decimal place). For example, try typing pi:10.

The result is a vector of real numbers starting with pi (3.142…) and increasing in increments of 1. The upper limit of 10 is never reached, since the next number in our sequence would be greater than 10.

Note also that pi is one of the few constants built in to R. Type ?pi to check the others.

What happens if we do 15:1? Give it a try to find out.

It counted backwards in increments of 1! This is sometimes useful for plotting coefficients from models in reverse order.

Remember that if you have questions about a particular R function, you can access its documentation with a question mark followed by the function name: ?function_name_here. However, in the case of an operator like the colon used above, you must enclose the symbol in backticks like this: ?:. (NOTE: The backtick (`) key is generally located in the top left corner of a keyboard, above the Tab key. If you don’t have a backtick key, you can use regular quotes.)

Pull up the documentation for : now.

Often, we’ll desire more control over a sequence we’re creating than what the : operator gives us. The seq() function serves this purpose.

The most basic use of seq() does exactly the same thing as the : operator. Try seq(1, 20) to see this.

This gives us the same output as 1:20. Check the help file for seq().

The help files show the arguments listed for the seq() function. The first two arguments are “from =” and “to =”. In R, you do not have to specify the arguments by name if you write out their values in the same order as written in the function. However, for complex functions it is often best practice to do so and makes your code much clearer.

For example, seq(from = 1, to = 20) will give the same output as seq(1, 20). Try it!

OK, let’s say that instead of 1 to 20, we want a vector of numbers ranging from 0 to 10, incremented by 0.5. seq(0, 10, by = 0.5) does just that. Try it out.

Or maybe we don’t care what the increment is and we just want a sequence of 30 numbers between 5 and 10. seq(5, 10, length = 30) does the trick. Give it a shot now and store the result in a new variable called my_seq.

If you look closely again at the help file for ?seq, you will not see an argument “length =”, but only “length.out =”. You can actually use any abbreviation of the argument name, as long as it is different from any other argument. You could even use just “l =”!

To confirm that my_seq has length 30, we can use the length() function. Try it now. To do this, you need to include the object ‘my_seq’ as the value of argument ‘x’ of length().

Let’s pretend we don’t know the length of my_seq, but we want to generate a sequence of integers from 1 to N, where N represents the length of the my_seq vector. In other words, we want a new vector (1, 2, 3, …) that is the same length as my_seq.

There are several ways we could do this. One possibility is to combine the : operator and the length() function like this: 1:length(my_seq). Give that a try.

Another option is to use seq(along.with = my_seq). Give that a try.

However, as is the case with many common tasks, R has a separate built-in function for this purpose called seq_along(). Type seq_along(my_seq) to see it in action.

There are often several approaches to solving the same problem, particularly in R. Simple approaches that involve less typing are generally best. It’s also important for your code to be readable, so that you and others can figure out what’s going on without too much hassle.

If R has a built-in function for a particular task, it’s likely that function is highly optimized for that purpose and is your best option. One of the philosophies of R (and Unix more generally) is to have tools (or functions) that do specific things very well and then link these together, rather than a single multi-purpose tool that does many things poorly.

This approach is like having a seperate knife, fork, and spoon, rather than a Spork … In most situations, cutlery (“silverware”) is superior to the Spork.

As you become a more advanced R programmer, you will learn how to link and nest these apparently simple functions to do incredibly powerful tasks. You will also design your own functions to perform tasks when there are no better options. We’ll explore writing your own functions in future lessons.

OK, back to the show. One more function related to creating sequences of numbers is rep(), which stands for ‘replicate’. Let’s look at a few uses.

If we’re interested in creating a vector that contains 40 zeros, we can use rep(0, times = 40). Try it out.

If instead we want our vector to contain 10 repetitions of the vector (0, 1, 2), we can do rep(c(0, 1, 2), times = 10). Go ahead.

Finally, let’s say that rather than repeating the vector (0, 1, 2) over and over again, we want our vector to contain 10 zeros, then 10 ones, then 10 twos. We can do this with the each argument. Try rep(c(0, 1, 2), each = 10).

Congratulations! Now you have several powerful tools that you can use to generate sequences of numbers. You also learnt to use the function length() and the ‘:’ operator. Your R skills are building!

Please submit the log of this lesson to Google Forms so that Simon may evaluate your progress.

[3]
Edit
Query
Report
Caoilinn Pani
Chief Visibility Officer
Answer # 3 #

The interpretation of the unnamed arguments of seq and seq.int is not standard, and it is recommended always to name the arguments when programming.

seq is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

seq.int is an internal generic which dispatches on methods for "seq" based on the class of the first supplied argument (before argument matching).

Typical usages are

The first form generates the sequence from, from+/-1, …, to (identical to from:to).

The second form generates from, from+by, …, up to the sequence value less than or equal to to. Specifying to - from and by of opposite signs is an error. Note that the computed final value can go just beyond to to allow for rounding error, but is truncated to to. (‘Just beyond’ is by up to \(10^{-10}\) times abs(from - to).)

The third generates a sequence of length.out equally spaced values from from to to. (length.out is usually abbreviated to length or len, and seq_len is much faster.)

The fourth form generates the integer sequence 1, 2, …, length(along.with). (along.with is usually abbreviated to along, and seq_along is much faster.)

The fifth form generates the sequence 1, 2, …, length(from) (as if argument along.with had been specified), unless the argument is numeric of length 1 when it is interpreted as 1:from (even for seq(0) for compatibility with S). Using either seq_along or seq_len is much preferred (unless strict S compatibility is essential).

[1]
Edit
Query
Report
Answer # 4 #

In this R tutorial, you will learn how to generate sequences of numbers in R. There are many reasons why we would want to generate sequences of numbers. For example, we may want to generate sequences when plotting the axes of figures or simulating data.

As often there is no one way to perform a specific task in R. In this post, we are going to use the : operator, the seq(), and rep() functions. First, we start having a look at the : operator. Second, we dive into the seq() function including the arguments that we can use. Third, we will have a look at how we can use the rep() function to generate e.g. sequences of the same numbers or a few numbers.

The absolutely simplest way to create a sequence of numbers in R is by using the : operator. Here’s how to create a sequence of numbers, from 1 to 10:

As you can see, in the image above, that gave us every integer from 1 and 10 (an integer is every positive or negative counting number, including 0). Furthermore, the created sequence is in ascending order (i.e., from the smallest number to the largest number). We will soon learn how to generate a sequence in descending order. First, however, if we want our sequence, from 1 to 10, to be saved as a variable we have to use the <- and create a vector:

Now, you might already have guessed that we can just change the order of the smallest and largest numbers to generate a sequence of numbers in descending order:

Note, that if you want to know more about a particular R function, you can access its documentation with a question mark followed by the function name: ?function_name_here.

In the particular case, however, an operator like the colon we used above, you must enclose the symbol in backticks like this: ?’:’.  Before we go to the next section it is worth mentioning that you can also use R to transpose a matrix or a dataframe.

Often, we desire more control over a sequence we are creating than what the : operator will give us. The seq() function serves this purpose and is a generalization of the : operator, which creates a sequence of numbers with a specified arithmetic progression.

Now, the most basic use of seq(), however, works the same way as the : operator does. For example, if you type seq(1, 10) this will become clear. That is, running this command will generate the same sequence as in the first example:

Evidently, we got the same output as using the : operator. If we have a look at the documentation we can see that there are number of arguments that we can work with:

As you can see in the image above (or in the documentation): the first two arguments of seq() are “from =” and “to =”. In R, we do not have to use the name of the arguments. That is, if we write out their values in the same order as written in the function it will produce the same results as using the names. It is worth noting, however, for more complex functions best practice is to use the names of the arguments. This will also make the code much clearer. For example, we can generate a sequence of descending numbers like this:

In the next subsection, we will have a look at the “by=” argument that enables us to define the increment of the sequence.

In some cases, we may want,  instead of 1 to 20, a vector of numbers ranging from 0 to 20, sequences incremented by e.g. 2. Here’s how to create a sequence of numbers with a specified increment step:

As you can see, in the image below, this produces a vector with fewer numbers but every number is increased by 2. In the next section, we will have a look at how to specify how many numbers we want to generate between two specified numbers.

Here’s how we can use the length argument to generate 30 numbers between 1 and 30:

Now, this generated 30 floating-point numbers between 1 and 30. If we want to check whether there really are 30 numbers in our vector we can use the length() function:

Now, as previously mentioned there are often many different approaches for solving the same problems. This is, of course, also for R statistical programming language. In general, choosing the simplest approach which includes as little code as possible is probably the way to go. That said, we will go to the next section where we will be learning to get a sequence of the same number (e.g, “0”). In a more recent post, you will learn 7 examples of when and how to use the %in% operator in R.

To get a repeated sequence of a number we can use the rep() function. Here’s how to create a vector containing 10 repetitions of the number 0:

Now, the rep() function can also be used together with the : operator, the c() or the seq() functions.

In this example, we are going to get the numbers 1, 2, 3 generated 10 times. Here’s how to repeat a sequence of numbers.

If we, on the other hand, want to replicate a sequence (e.g., 1 to 5) 10 times we can use the : operator:

Finally, it is also possible to get each number, that we want in our sequence, to be generated a specified amount of times:

Note, that if we want to repeat a function or generate e.g., sequences of numbers we can use the repeat and replicate functions in R. as well.

Check out the following posts if you need to extract elements from datetime in e.g. a vector:

[0]
Edit
Query
Report
Barbie Janssens
Pewterer
Answer # 5 #

Let’s dive !!!

Seq(): The seq function in R can generate the general or regular sequences from the given inputs.

Where:

Well, I know you are super excited to generate a sequence using seq() in R. Without much delay, let’s see how it works.

In this sample, the first number represents ‘from’ and last number represents ‘to’ arguments.

Serial Numbers:

Output:

1 2 3 4 5 6 7 8 9 10

Decimal Numbers:

Output:

1 2 3 4 5 6 7 8 9 10

Negative Numbers:

Output:

-1 -2 -3 -4 -5 -6 -7 -8 -9 -10

In this section, along with from and to arguments, we are using ‘by’ argument as well.

The by argument will increment the given number in the sequence as shown below.

Here, I am illustrating the sample using the keywords as well for the proper view.

The Output:

1 3 5 7 9

In the above output, you can observe that the argument ‘by’ increments the sequence by 2 i.e. The beginning number of the sequence 1 gets incremented by 2 each time till the sequence ends at 10.

Result:

3 6 9 12 15 18 21 24 27 30

You can also do this without keywords if you know the syntax well. You will get the same output without keywords. But it’s always recommended to use the keywords for proper documentation and readability.

The Result:

3 6 9 12 15 18 21 24 27 30

Length.out is the argument that decides the total length of the sequence.

Let’s see how it works with some illustrations:

Output:

3 6 9 12 15 18 21 24 27 30

As you can observe in the above output, the length.out argument will structures the sequence with the specified length.

Let’s use this argument to generate a negative sequence.

Output =

-3 -6 -9 -12 -15 -18 -21 -24 -27 -30

Along.with argument takes an input vector and outputs a new sequence of the same length as the input vector within the specified range of numbers.

Don’t worry about the above lines too much. I will illustrate this with simple examples.

Output:

1 9 17 25

Output:

-5.00 -1.25 2.50 6.25 10.00

As the headline says, you can use seq() functions with some arguments with ease. Yes, you heard it right!.

If you wonder, how you can pass the arguments to seq() directly, don’t worry. Follow the below illustration to understand this easily.

Output =

1 2 3 4 5

Output =

1 2 3 4 5 6 7 8 9 10

Output =

Error in seq_len(-10): argument must be coercible to non-negative integer

-5 -4 -3 -2 -1 0 1 2 3 4 5

2 3 4 5 6 7 8 9 10

The seq() function in R is a valuable addition to the list of functions present in R. Using the function, you can generate the regular sequences by passing various arguments as well.

[0]
Edit
Query
Report
tyzl Theatre
GEM CUTTER