-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14 functions.r
More file actions
85 lines (66 loc) · 1.54 KB
/
14 functions.r
File metadata and controls
85 lines (66 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# To call a function, use the function name followed by parenthesis, like my_function():
my_function <- function() {
print("Hello World!")
}
my_function() # call the function named my_function
my_function <- function(fname) {
paste(fname, "Mayank")
}
my_function("hello")
my_function("hi")
my_function("namaste")
# number of arguments
my_function <- function(fname, lname) {
paste(fname, lname)
}
my_function("Mayank", "Kumar")
# Default Parameter Value
my_function <- function(country = "Norway") {
paste("I am from", country)
}
my_function("Sweden")
my_function("India")
my_function() # will get the default value, which is Norway in this case
my_function("USA")
# Return Values Example 1
my_function <- function(x) {
return (5 * x)
}
print(my_function(3))
print(my_function(5))
print(my_function(9))
# Return Values Example 2
new_function <- function(x){
return (7 + x)
}
print (new_function(8))
print (new_function(9))
print (new_function(7))
# Nested Functions
# 1. By Calling a function within another function.
Nested_function <- function(x, y) {
a <- x + y
return(a)
}
Nested_function(Nested_function(2,2), Nested_function(3,3))
# By Writing a function within a function
Outer_func <- function(x) {
Inner_func <- function(y) {
a <- x + y
return(a)
}
return (Inner_func)
}
output <- Outer_func(3) # To call the Outer_func
output(5)
# Recursion function
tri_recursion <- function(k) {
if (k > 0) {
result <- k + tri_recursion(k - 1)
print(result)
} else {
result = 0
return(result)
}
}
tri_recursion(6)