R Data Types

Introduction

Understanding data types is fundamental to effective programming in R, as they determine the kinds of operations you can perform on your data. In this chapter, you will learn the basic data types in R, including numeric, integer, complex, logical, character, and factor types.

Basic Data Types in R

1. Numeric

Numeric data types represent real numbers and are the default type for numbers in R.

Example:

# Numeric data type
num <- 10.5
print(num)          # Output: 10.5
print(class(num))   # Output: "numeric"

2. Integer

Integer data types represent whole numbers. You can explicitly define an integer by adding an L suffix.

Example:

# Integer data type
int <- 10L
print(int)          # Output: 10
print(class(int))   # Output: "integer"

3. Complex

Complex data types represent complex numbers with real and imaginary parts.

Example:

# Complex data type
comp <- 3 + 2i
print(comp)         # Output: 3+2i
print(class(comp))  # Output: "complex"

4. Logical

Logical data types represent Boolean values: TRUE or FALSE.

Example:

# Logical data type
bool <- TRUE
print(bool)         # Output: TRUE
print(class(bool))  # Output: "logical"

5. Character

Character data types represent text or string values.

Example:

# Character data type
char <- "Hello, R!"
print(char)         # Output: "Hello, R!"
print(class(char))  # Output: "character"

6. Factor

Factors are used to represent categorical data and can be ordered or unordered. Factors are particularly useful for statistical modeling.

Example:

# Factor data type
factor_data <- factor(c("low", "medium", "high", "medium", "low"))
print(factor_data)          # Output: [1] low    medium high   medium low
                            # Levels: high low medium
print(class(factor_data))   # Output: "factor"

Conclusion

In this chapter, you learned about the basic data types in R: numeric, integer, complex, logical, character, and factor types. Each data type serves a specific purpose and understanding them is crucial for performing various operations in R. Whether you are working with numbers, text, or categorical data, knowing the appropriate data type to use will help you write more efficient and effective R programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top