Condition, Loops and functions
Code:
#If Else:
x = 0
if (x >= 0) {
print('Positive Number')
}
if (x >= 0) {
print('Positive Number')
} else {
print('Negative Number')
}
if (x > 0) {
print('Positive Number')
} else if (x < 0) {
print('Negative Number')
} else{
print('Zero Number')
}
x <- -5
ifelse(x>=0,'Positive Number','Negative Number')
x <- c(10,45,30,50,35,40,80,25)
ifelse(x%%2==0,1,0)
For Loop
for(i in 1:5)
print(i)
for(i in 1:5) {
print(i)
}
#for(i in 1:5)
# i #doesnt work should use print
x <- 1:5
for(i in seq_along(x))
print(x[i])
for(i in x) {
print(i) #prints every element of the list
}
for(i in x) print(i) #prints every element of the list
x <- 'Hello'
for(i in x)
print(i)
While Loop
i <- 0
while(i<5){
print(i)
i <- i + 1
}
Repeat Loop
i <- 0
repeat {
print(i)
if (i>=5)
break
i <- i + 1
}
Break Next
i <- 0
repeat {
print(i)
if (i>=5)
break
i <- i + 1
}
for(i in 1:10) {
if(i%%2==0)
next
print(i)
}
Functions
sum = function(x,y) {
z = x + y
return (z)
}
sum(20,30)
sum = function(x=10,y=20) {
z = x + y
return (z)
}
sum = function(x,y=20) {
z = x + y
return (z)
}
sum = function(x=10,y) {
z = x + y
return (z)
}
#Lazy Evaluation
sum = function(x,y,w) {
z = x + y
return (z)
}
#Returning Multiple Values
sum = function(x,y) {
z = x + y
w = x * y
res = list('a'=z,'m'=w)
return (res)
}
#Inline Functions
f1 = function(x) x^3
f2 = function(x,y) x^y
Comments
Post a Comment