Introduction to Object-Oriented Programming

Beatriz Manso
2021-10-14

Object-oriented Programming

Object-oriented programming is a programming paradigm built on the concept of objects that contain both data and code to modify the data. Object-oriented programming mimics a lot of the real-world attributes of objects. Some of the most widely used object-oriented programming languages are Java, C++, and Ruby.

Programming exercises

1. Declare a variable

To assign a value to a variable in a data type in R programming, use <- or =.

variable1 <- 9
variable2 = 'value'

2. Define a vector

The simplest way to build a vector data structure in R is to use the c command.

vec_num <- c(1, 10, 49)
vec_num
[1]  1 10 49
vec_chr <- c("a", "b", "c")
vec_chr
[1] "a" "b" "c"

3. If statement

a <- 33
b <- 33
if (b > a) {
 print("b is greater than a")
} else if (a == b) {
 print ("a and b are equal")
}
[1] "a and b are equal"

4. While loop

i <- 1
while (i < 6) {
 print(i)
 i <- i + 1
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

5. For loop

fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
 print(x)
}
[1] "apple"
[1] "banana"
[1] "cherry"

6. Functions

my_function <- function() { 
 print("Hello World")
}
my_function()
[1] "Hello World"

7. Global Variables:

A global variable can be used by any object, both inside and outside of a function

txt <- "awesome"
my_function <- function() {
 paste("R is", txt)
}
my_function()
[1] "R is awesome"

8. R program

# create a function with the name my_function
my_function_2 <- function() {
 print("My function!")
}

# call the function
my_function()
[1] "R is awesome"
#Vector 1 and 2
vect_1 <- c(1, 3, 5)
vect_2 <- c(2, 4, 6)

# Compute the sum of vector_1 and vector_2
sum_vect <- vect_1 + vect_2

# Display the sum of the vevctors on the screen
sum_vect
[1]  3  7 11