R Programming – Functions & IFELSE statement

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:-
myfirstfn <- function(x) {x+x}
myfirstfn(10)
image
Example 2:
mysecondfn <- function(t,z) {     
value = z*3      
value = value *t      
print(value)}


t= 5
z= 9

mysecondfn(t,z)

image

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)
image

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)
image
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)
image
x=10
ifelse (x<5, "target", NA)
    
image
Example 6:-
x=c(4,5,6)

ifelse(x < 5, "smaller than",
       ifelse(x==5, "equal to", "greater than"))
image
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
image
R Programming – Functions & IFELSE statement R Programming – Functions & IFELSE statement Reviewed by Pubudu Dewagama on 9:50:00 PM Rating: 5

No comments: