R has four different functions that tell you the type of a variable, namely class
, typeof
, mode
, and storage.mode
. For some variable types they all give the same answer, but for others they differ, and it gets a little bit complicated.
For the vast majority of code you write, you’ll only ever care about the class
. The only time class
can’t help you is when you are examining matrices or arrays, and you care about whether the variable contains numbers or characters (or some other type). In this case, you can use one of the other three type functions, or call one of the is.*
functions (is.numeric
, for example).
Table A-1 shows the values returned by class
, typeof
, mode
, and storage.mode
for various variable types.
Table A-1. Comparison of variable class, type, mode, and storage mode
class | typeof | mode | storage.mode | |
---|---|---|---|---|
Logical |
|
|
|
|
Integer |
|
|
|
|
Floating Point |
|
|
|
|
Complex |
|
|
|
|
String |
|
|
|
|
Raw byte |
|
|
|
|
Categorical |
|
|
|
|
Null |
|
|
|
|
Logical Matrix |
|
|
|
|
Numeric Matrix |
|
|
|
|
Character Matrix |
|
|
|
|
Logical Array |
|
|
|
|
Numeric Array |
|
|
|
|
Character Array |
|
|
|
|
List |
|
|
|
|
Data Frame |
|
|
|
|
Function |
|
|
|
|
Environment |
|
|
|
|
Expression |
|
|
|
|
Call |
|
|
|
|
Formula |
|
|
|
|
In R, vectors are variable types with a length, but no dimension (that is, dim
returns NULL
) and no attributes other than names. Vector types include numeric, logical, and character types, but also lists and expressions. The rule about no attributes means that factors are not vectors.
Lists are vectors. Factors are not vectors.
Related to vectors are atomic types. Atomic means that a type cannot contain other instances of that type within itself. The opposite of atomic is recursive: lists are the canonical example, since they can contain other lists. An object can only ever be atomic or recursive, never both.
Matrices and arrays are atomic.
Some objects are known as language objects. These variable types can be evaluated to run R code.
Table A-2 shows the values returned by is.vector
, is.atomic
, is.recursive
, and is.language
for various variable types.
Table A-2. Comparison of which variable types are vectors, atomic, recursive, or language objects
is.vector | is.atomic | is.recursive | is.language | |
---|---|---|---|---|
Logical |
|
|
|
|
Integer |
|
|
|
|
Floating Point |
|
|
|
|
Complex |
|
|
|
|
String |
|
|
|
|
Raw Byte |
|
|
|
|
Categorical |
|
|
|
|
Null |
|
|
|
|
Logical Matrix |
|
|
|
|
Numeric Matrix |
|
|
|
|
Character Matrix |
|
|
|
|
Logical Array |
|
|
|
|
Numeric Array |
|
|
|
|
Character Array |
|
|
|
|
List |
|
|
|
|
Data Frame |
|
|
|
|
Function |
|
|
|
|
Environment |
|
|
|
|
Expression |
|
|
|
|
Call |
|
|
|
|
Formula |
|
|
|
|