Get startedGet started for free

Useful Functions

1. Useful Functions

2. Loads of useful functions

By now, you surely have some idea of the huge amount of useful functions that are available in R. The functions of the apply family that you've learned about before are just an illustration of this diversity. Along the way you also used the sort function, the print function, the identical function, and many more. In this video, I'm going to talk about a number of easy, but very often used functions in the R language. First, I'm going to talk about some math-related functions and next, I'll head over to functions that relate more closely to R's data structures. If you aced all the previous exercises, you should recognize some of them.

3. Mathematical utilities

Have a look at the following R code that uses several mathematical functions. The first two lines of code are nothing new; they simply create two vectors, v1 and v2. The last line of code is less straightforward so let's chop it up into pieces and see what each of the function components does along the way.

4. abs()

The innermost function, abs() calculates the absolute value of an array of numerical values, in our case the vectors v1 and v2. I went ahead and already replaced the variable names with the actual vectors that they represent. The result is what we would expect. We get the positive value of all elements. Let's replace the vectors that result from calling the abs() functions in the expression, giving us the following line.

5. round()

The next inner function that we encounter is the round() function, which rounds the input. In the first round function, 1 (point) 1 gets rounded to 1, while 2 (point) 7 is rounded to 3. In the second round call 3 (point) 6 becomes 4 and 8 (point) 0 becomes 8.

6. sum()

If we replace the round() functions with their results, we arrive at the sum() function. This function simply computes the sum of the input array. If you pass a matrix as an argument to the sum function, for example, the sum of all the matrix elements gets returned. In our example, a vector is passed to the sum function, so R simply calculates the sum of the vector elements. The first sum is 16, while the second sum equals 22. We've almost broken down our expression entirely if we fill in the results of both the sum calls.

7. mean()

The mean function calculates the arithmetic mean. Again, mean() is a generic function that is capable of handling different types of R objects, but most commonly you would use it on numerical arrays. In our case, the input to mean is a vector of length 2, containing the values 16 and 22. Recalling our primary school level math, it isn't a surprise that the result of this call is 19. Finally! We arrive at the end of our bulky arithmetic one-liner: the result is 19. This corresponds to the result that we get when we execute the code chunk we began with.

8. Functions for data structures

This was still pretty easy, right? Let's head over to the next example to introduce some of the functions you'll often use when creating and manipulating data structures. Take a close look at this big fella'. No need to panic! There are some things we already know here. The list() function creates a list. Apparently, there are three list elements, named log, ch and int_vec. log is simply a logical, TRUE, ch is a character string, hello, but what about int_vec? Let's have a closer look. The innermost function here, is the seq() function

9. seq()

seq generates a sequence of numbers. The first two arguments tell R the limits of the sequence. That is, where to start and end the sequence, respectively. The by argument specifies the increment value for the sequence on each step. For instance, this line of code would generate a sequence starting at 1, going to 10, with steps of size 3. For our example, the seq function call would read as: generate a sequence from 8 to 2, while taking steps of -2. We get a vector of length 4. As before, let's go ahead and fill in the resulting vector to simplify the expression for int_vec.

10. rep()

We now arrive at the rep() function. The rep() function has the ability to replicate its input, which typically is a vector or a list. Using the times argument, we can specify how the replication should happen. If the times argument is a vector of length 1, it tells rep() how often the entire structure should be repeated. This is the case in our example, which results in a vector of length 8. You could also use the each argument inside rep. Instead of repeating the entire vector, every element gets repeated. Can you spot the difference? There are more advanced ways of using rep() which I won't detail here. Remember, help is just a single question mark (?) away in R! So our rep() call with the times argument results in a vector of length 8. Let's go ahead an replace the call with this result.

11. sort()

Finally, the sort() function is a generic function for sorting an input vector. You can use it on numerical values, but also on character and logical vectors. It works as you would expect, sorting the input vector in ascending order. By setting the decreasing argument, which is FALSE by default, to TRUE, we can reverse the order of arranging. So that's that. We've reverse engineered the bulky expression for the int_vec element inside our list. To check if we decomposed this expression correctly

12. sort()

let's see what a direct evaluation looks like. Looks good! We thus end up with the following list definition.

13. str()

Remember the str() function to inspect the structure of this list? It's a great function to see the contents of your data structures in a concise way. Before you can roll up your sleeves for the some of the interactive exercises

14. is.*(), as.*()

have a look at the following R expression. The is (dot) functions are functions you can use to check the type of your data structure. They return a logical. Because li is a list, is (dot) list of li returns TRUE. On the other hand, is (dot) list on a vector returns FALSE. Instead of is (dot) function, R also provides the as (dot) functions. These can be used to convert vectors to lists, for example. Now, calling is (dot) list on li2 will return TRUE as the vector was converted to a list using as (dot) list().

15. is.*(), as.*()

Next, there might be some cases in which you want to convert your list to a vector. In these cases, you might want to use the unlist function. R flattens the entire list structure and returns a single vector. Notice the coercion here. Because vectors can only contain a single atomic type, the logical TRUE and the numerical vector are all coerced to character strings. Also notice how R tries to come up with meaningful names for all vector elements.

16. append(), rev()

Finally, you should definitely check out the append() and rev() functions. The append() function allows you to add elements to a vector or a list in a very readable way. In combination with the rev() function, which reverses elements in a data structure, we could create a new version of li that contains the same data in the different order. The rev() function first reverses the list, placing the int_vec vector first and the log value, TRUE last.

17. append(), rev()

Afterwards, append() concatenates the original vector li and its reversed version to create a list of 6 elements, double li's length. Notice how I used the str() function here to inspect the structure.

18. Let's practice!

Head over to the exercises to experience all of this data structure juggling and mathematical supercharging yourself! Have fun!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.