Home / Programs / Write a function in R programming Language which will take parameter and the value will default value.
Programming Example

Write a function in R programming Language which will take parameter and the value will default value.

👁 354 Views
💻 Practical Program
📘 Step by Step Learning
Write a function in R programming Language which will take parameter and the value will default value.

Program Code

# R function

hello.person <- function(firstName, lastName = "Ansari")
{
  print(sprintf("Hello %s %s", firstName, lastName))
}

# different way of function calling
hello.person("Rumman")

hello.person(firstName = "Rumman")

hello.person(firstName = "Ansari", "Azmi")

# this function calling will not work
hello.person(lastName = "Rumman")

Output

> hello.person("Rumman")
[1] "Hello Rumman Ansari"
> 
> hello.person(firstName = "Rumman")
[1] "Hello Rumman Ansari"
> 
> hello.person(firstName = "Ansari", "Azmi")
[1] "Hello Ansari Azmi"
> # this function calling will not work
> hello.person(lastName = "Rumman")
 Error in sprintf("Hello %s %s", firstName, lastName) : 
  argument "firstName" is missing, with no default

Explanation

# this function calling will not work hello.person(lastName = "Rumman")

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.