Functions
Ek function function(args) { body } se banaya jata hai aur <- se ek naam ko assign kiya jata hai, kisi bhi doosri value ki tarah hi — functions koi special syntax nahi hain, ye ordinary values hain jinhein aap call kar sakte hain. Arguments ki default values ho sakti hain, = se supplied, jo istemal hoti hain jab caller us argument ko explicitly pass nahi karta. Ek function ka return value uska last evaluated expression hota hai — koi return keyword zaroori nahi, wohi implicit-return style jo Ruby istemal karta hai.
greet <- function(name, greeting = "Hello") {
paste(greeting, name)
}
print(greet("World"))
print(greet("R", "Hi"))
[1] "Hello World" [1] "Hi R"
greet("World") ne default greeting "Hello" istemal kiya kyunke koi supply nahi ki gayi thi; greet("R", "Hi") ne isay override kiya. Dono calls ko explicit return(paste(...)) ki zaroorat nahi padi — function ka single expression, paste(greeting, name), khud ba khud wohi hai jo wapas ata hai. Aage: vectors vs. lists — list(), heterogeneous collections, aur [ ] aur [[ ]] ke beech ka real difference.
Practice exercise
square <- function(x) likho jo x^2 return kare implicit return istemal kar ke (baghair return keyword ke), phir square(7) print karo.