R functions are OBJECTS and they do calculations for you
R function structure: name function (argument) {statements} # the arguments specify the components to be used in the function
Example 1:-
Example 2:
Example 3:-
In this case the object "value" was used stepwise within the function and triple dots can be used as a place holder, for any argument to be used
as you can see it is a dataframe, every row is numbered and you can use the function in any way you want as long as the vectors have the appropriate length
IFELSE statement
IFELSE is used to incorporate logical conditions in functions and bit different to the IF statement (loop section)
Syntax: ifelse (logical condition or test, calculation if yes, calculation if no)
Example 5:-
Example 6:-
Example 7:-
R function structure: name function (argument) {statements} # the arguments specify the components to be used in the function
Example 1:-
myfirstfn <- function(x) {x+x}
myfirstfn(10)
Example 2:
mysecondfn <- function(t,z) {
value = z*3
value = value *t
print(value)}
t= 5
z= 9
mysecondfn(t,z)
Example 3:-
In this case the object "value" was used stepwise within the function and triple dots can be used as a place holder, for any argument to be used
testfunction <- function(...){
mydataframe = data.frame(cbind(...))
print(mydataframe)}
a = (4:7)
b = c("a","g","h","w")
testfunction(a,b)
as you can see it is a dataframe, every row is numbered and you can use the function in any way you want as long as the vectors have the appropriate length
c = c(4.6, 5.5, 8.9, 11.3)
testfunction(c,b)
IFELSE statement
IFELSE is used to incorporate logical conditions in functions and bit different to the IF statement (loop section)
Syntax: ifelse (logical condition or test, calculation if yes, calculation if no)
Example 5:-
x=4
ifelse (x<5, "target", NA)
x=10
ifelse (x<5, "target", NA)
Example 6:-
x=c(4,5,6)
ifelse(x < 5, "smaller than",
ifelse(x==5, "equal to", "greater than"))
Example 7:-
ifelsefun <- function(y,z){
ifelse(y<7, y+z, "above target")}
ifelsefun(4,2) # lets test a positive
ifelsefun(40,7) # this one should be a negative
R Programming – Functions & IFELSE statement
Reviewed by Pubudu Dewagama
on
9:50:00 PM
Rating:
No comments: