Scoping_Arguments_Functions_R and Userdefined.pptx

geethar79 5 views 10 slides Oct 27, 2025
Slide 1
Slide 1 of 10
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10

About This Presentation

Scoping_Arguments_Functions_R.pptx


Slide Content

Scoping, Argument Matching, and Writing Functions in R R Programming – Notes & Presentation

Objectives • Understand scoping rules in R • Learn how R matches function arguments • Write and use custom functions

Scoping Overview • Scoping determines how R finds variable values. • R uses Lexical Scoping (not Dynamic Scoping). • Search order: 1. Local Environment 2. Parent Environment 3. Global Environment 4. Base Environment

Lexical Scoping Example Example: x <- 10 f <- function() { x <- 5 g <- function() x + 1 g() } f() # Output: 6

Argument Matching Rules R matches arguments using three rules: 1. Exact Matching by Name 2. Partial Matching by Name 3. Positional Matching

Argument Matching Example fun <- function(a, b, c) print(c(a, b, c)) fun(a=1, b=2, c=3) # Exact fun(a=1, b=2, c=3) # Partial fun(1, 2, 3) # Positional

Writing Functions in R Syntax: function_name <- function(arg1, arg2, ...) { # body return(value) } Example: add_numbers <- function(x, y) { sum <- x + y return(sum) } add_numbers(10, 5) # Output: 15

Default and Variable Arguments • Default values can be assigned: greet <- function(name = "User") { paste("Hello", name) } • Use ... to handle multiple arguments: print_all <- function(...) print(list(...)) print_all(1, 2, "R", TRUE)

Specialized Functions Common specialized functions in R: • Math: sqrt(x), log(x), mean(x) • Statistical: sd(x), var(x), summary(x) • Character: toupper("r"), substr("data",1,2) • Apply-family: apply(), lapply(), sapply()

Summary • Scoping defines variable search rules (R uses lexical scoping). • Argument matching: exact, partial, or positional. • Functions are created using function() and can have default or variable arguments. • Specialized functions are built-in for math, stats, and text manipulation.