Copy and paste the following code to your R Studio platform or R version:

# If statements

months.employed <- 5
base.salary <- 5000
bonus <- 0

if(months.employed > 3) {

bonus <- base.salary * 0.10

}
print(bonus)

if(months.employed > 10) {

bonus <- base.salary * 0.25
print(bonus)
print(“Entered the if case”)

} else {

bonus <- base.salary * 0.10
print(bonus)
print(“Entered the else case”)

}

if(months.employed > 12) {

bonus <- base.salary * 0.40
print(bonus)
print(“Entered the if case”)

} else if (months.employed > 6 && months.employed <= 12) {

bonus <- base.salary * 0.20
print(bonus)
print(“Entered the else if case”)

} else {

bonus <- base.salary * 0.10
print(bonus)
print(“Entered the else case”)

}

# The switch statement
vec1 <- c(1, 3, 4, 8)

x <- 1
result <- switch(x, mean(vec1), median(vec1))
result

x <- 2
result <- switch(x, mean(vec1), median(vec1))
result

# Functions in R

body.mass.index <- function(weight, height) {

index <- weight/(height*height)
return(index)
}

bmi <- round(body.mass.index(65, 1.75), 1)
print(bmi)

# Lazy evaluation

test.function <- function(a, b) {

print(a)

}

test.function(1, 2)
# it prints only the first argument, since the second is not used
# inside the function, it does not create an error

test.function(3)

test.function <- function(a, b) {

print(a)
print(b)

}

test.function(3)
# now we get an error –> Error in print(b) : argument “b” is missing, with no default

test.function(a = 5, b = 10)
test.function(b = 3, a = 23)
# explicitly defining the arguments of the function

Posted by Dimitris

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s