In R programming, there are five basic data types. Also, everything in R is an object, so we will refer to these data types as classes of objects. So, these five types of objects are:
Let's briefly look at each of these.
In R, decimal values such as 8.5 are numeric. You can assign a numeric value to a variable and then that variable will be of numeric data type.
For any variable or object, you can check it's data type by using the class command.
1> # Assign a decimal value to x
2>
3> x <- 8.5
4>
5> # Print the value of x
6> x
7[1] 8.5
8>
9> # Print the class name of x
10>
11> class(x)
12[1] "numeric"
13>
14Integers are the natural numbers such as 1, 2, 3, etc. In R, when you assign a number to a variable, it is by default of the numeric class type. In order to create an integer variable, we use a function called as.integer(). This ensures that the variable created is indeed an integer.
1> #Assign a value to a variable
2> x <- 8
3>
4> #check the class type of x
5In R, a complex value is defined using a pure imaginary value <em>i</em>.
1> #Assign a complex value to a variable
2> x = 1 + 2i
3>
4> #Print the complex value x
5Logical values are boolen values (TRUE or FALSE) often created by comparison between variables.
1> #Create sample variables
2> x <- 5
3> y <- 7
4>
5Character values are string or text values. We can create a character type variable by assigning a string to the variable. Notice the use of double quotes.
1> #Create a character variable
2>
3> x <-"John Doe"
4>
5> #Print the character stringIf we have an object of some other data type (e.g., numeric), we can convert it into character type using the as.character() function.
1> #Create a numeric variable
2>
3> x <- 8.75
4>
5> We can perform standard logical operations such as "&" (and), "|" (or), and "!" (negation) on logical values in R.
1> x = TRUE; y = FALSE
2> x & y # Checks that both x AND y are true
3[1] FALSE
4> x We can easily perform basic string operations in R such as concatenation, or creating readable strings.
1> #Define sample character variables
2> fname <- "John"
3> lname <- 'Doe'
4>
The sprintf() function allows you to create strings as output using formatted data. For example:
1sprintf("I go for a walk at %s:%s%s a.m.", 7, 0, 5)
2This will output:
#> [1] "I go for a walk at 7:05 a.m."
See the special syntax %s. Each % is referred to as a slot, which is basically a placeholder for a variable that will be formatted. The values after the comma are the variables or values that will be filled in each slot.
We can find many more functions for these data types in the R documentation. For each function, the help also provides details about how to use these functions. For example, you can get help for sprintf() function by using the command help('sprintf'). The documentation will open in the help window (bottom right).