R Data Types
Data types in R define the nature of data stored in variables. Understanding R's basic data types is crucial for data analysis and manipulation. R primarily supports the following data types: numeric, integer, character, logical, complex, and raw.
Key Topics
1. Numeric
Numeric data type in R is used for numbers with or without decimals.
# Numeric example
num <- 10.5
print(num)
Output:
Code Explanation: The variable num
is assigned a numeric value of 10.5. The print()
function outputs this value to the console.
2. Integer
Integer data type is used for whole numbers and is specified with an L
suffix.
# Integer example
int_val <- 100L
print(int_val)
Output:
Code Explanation: The variable int_val
is assigned an integer value of 100, denoted by the L
suffix. This ensures the value is treated as an integer.
3. Character
Character data type is used for text or string values.
# Character example
name <- "Rohini"
print(name)
Output:
Code Explanation: The variable name
is assigned the string "Rohini". The print()
function displays this string in the console.
4. Logical
Logical data type represents boolean values: TRUE
or FALSE
.
# Logical example
is_active <- TRUE
print(is_active)
Output:
Code Explanation: The variable is_active
is assigned the boolean value TRUE
. The print()
function outputs this boolean value.
5. Complex
Complex data type is used to represent numbers with real and imaginary parts.
# Complex number example
comp <- 3 + 4i
print(comp)
Output:
Code Explanation: The variable comp
is assigned a complex number with a real part of 3 and an imaginary part of 4. The print()
function displays the complex number.
6. Raw
Raw data type is used to store raw bytes. Useful for binary data.
# Raw data example
raw_val <- charToRaw("Hello")
print(raw_val)
Output:
Code Explanation: The function charToRaw()
converts the string "Hello" into raw byte format. The print()
function displays the raw byte representation.
Key Takeaways
- R supports different data types for handling various kinds of data.
- Numeric and integer types are used for numerical data, while character type is for text data.
- Logical values are used for boolean operations, and complex numbers are supported for mathematical computations.
- Raw type is used for handling byte data.