Get startedGet started for free

How does R Distinguish Variables?

1. How does R Distinguish Variables?

You’ve already seen the str function for examining the structure of a variable.

2. str()

For example, if you call str on the sleep dataset, you can see that it is a data frame with 20 rows and 3 columns, and you can see some of the details of each column. Now you are going to see some more functions that interrogate your variables to determine their type. The most important of these functions is called class. Going back to the sleep dataset, if you call class on it, then you see the obvious result. That is, the sleep variable has class data-dot-frame, just as you saw when you called the str function. Most of the time class is the only function that you need to use to interrogate the type of your variable. Sometimes, however, you need to dig a little deeper, and there are three more functions to consider.

3. int_mat

Let’s take a look at a matrix. Notice that the class of this object is "matrix". This is what you might expect, and it’s useful to know, but doesn’t tell you everything. For example, there are different kinds of matrix. As well as numeric matrices, you can also have logical or character matrices. So how do you find out what the matrix contains? In this case, you can use the typeof function. Here you can see that the type is "integer". That is, you have an integer matrix. Now let's look at a numeric matrix.

4. num_mat

This time, rather than containing integers, you have floating point numbers. Again, of course, the matrix has class "matrix". But now when you call typeof, the return value is "double". This is because typeof returns the type of variable that R understands in its internal C language code. In C, floating point numbers are called doubles, so that's what typeof returns here. The important point is that you can use typeof to precisely determine the contents of your variable, regardless of its class. This is especially useful once you start working with S3. There are two other functions for determining the kind of object that you have,

5. mode()

namely mode and storage-dot-mode. These functions exist solely for compatibility with older S code, so while you need to know that they exist, you should never need to use them.

6. Summary

To summarise, most of the time you should use the class function to determine what kind of variable you have. Occasionally, typeof is useful as well. You may come across mode and storage-dot-mode in older code, but you shouldn't need to use them yourself.

7. Let's practice!

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.