Loading...
Loading...

R Data Types and Variables

Understanding data types is crucial for effective R programming. This tutorial covers R's fundamental data types and how to work with 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?

  • Numeric
  • Integer
  • Character

How would R store TRUE/FALSE values?

  • As integers (1/0)
  • As logical values
  • As factors

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?

  • FALSE
  • TRUE
  • Error

Which function checks the storage type?

  • typeof()
  • data.type()
  • check.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?

  • NA
  • NULL
  • NaN

What does 1/0 return in R?

  • NA
  • Inf
  • Error

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?

  • Represent categorical data
  • Store numeric ranges
  • Handle missing data

How do you check factor levels?

  • levels()
  • factors()
  • categories()
0 Interaction
2.1K Views
Views
48 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home