Understanding data types is crucial for effective R programming. This tutorial covers R's fundamental data types and how to work with variables.
R Data Types and Variables
1. Basic Data Types
R has several atomic data types:
# Numeric (both integer and double)
num <- 3.14
# Character (strings)
text <- "Hello R!"
# Logical (boolean)
flag <- TRUE
# Complex
comp <- 1 + 4i
# Raw (binary data)
raw_data <- charToRaw("hello")
Data Types Quiz
Which type would 3.14 be in R?
How would R store TRUE/FALSE values?
2. Checking and Converting Types
Use these functions to inspect and convert types:
# Check type
typeof(num) # Returns "double"
class(text) # Returns "character"
# Convert types
as.integer(3.14) # 3
as.character(123) # "123"
as.logical(1) # TRUE
Type Conversion Quiz
What does as.logical(0)
return?
Which function checks the storage type?
3. Special Values
R has several special values you'll encounter:
# Missing value
NA
# Not a number
NaN
# Infinite
Inf
# Null object
NULL
Note: NA
has different types (NA_integer_, NA_real_, etc.)
Special Values Quiz
What represents missing data in R?
What does 1/0 return in R?
4. Factors - Categorical Data
Factors represent categorical variables:
# Create a factor
gender <- factor(c("male", "female", "female", "male"))
# View levels
levels(gender) # Returns "female" "male"
# Ordered factor
temp_levels <- factor(c("low", "high", "medium"),
levels = c("low", "medium", "high"),
ordered = TRUE)
Factors Quiz
What's the main purpose of factors?
How do you check factor levels?
×