Variables and Data Types in R

R BasicsVariablesFree Lesson

Advertisement

Introduction

Variables in R are used to store data values. R is a dynamically typed language, meaning you don't need to declare the type of a variable explicitly.

Creating Variables

# Using assignment operator
x <- 10
y <- "Hello"
z <- TRUE

# Also,可以使用 = 
a = 25

Data Types in R

# Numeric
num <- 42.5
class(num)

# Integer
int <- as.integer(42)
class(int)

# Character (String)
char <- "R Programming"
class(char)

# Logical (Boolean)
logi <- TRUE
class(logi)

# Complex
comp <- 3 + 2i
class(comp)

Checking Data Types

# Check class
class(x)

# Check type
typeof(x)

# Check if numeric
is.numeric(x)

# Check if integer
is.integer(x)

# Check if character
is.character(x)

# Check if logical
is.logical(x)

Type Conversion

# Numeric to character
as.character(42)

# Character to numeric
as.numeric("42")

# Numeric to logical
as.logical(1)   # TRUE
as.logical(0)  # FALSE

# Logical to numeric
as.numeric(TRUE)  # 1
as.numeric(FALSE) # 0

Special Values

# NA - Missing values
NA

# NULL - Empty object
NULL

# NaN - Not a Number
0/0

# Inf - Infinity
1/0

Variable Naming Rules

# Valid variable names
my_var <- 1
myVariable <- 2
.variable <- 3
my_variable_2 <- 4

# Invalid (will cause error)
# 2var <- 5        # Can't start with number
# my-var <- 6      # Can't use hyphen

Summary

Understanding variables and data types is fundamental to R programming. R's dynamic typing makes it flexible and easy to work with.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement