Basic Operations#

Assigning Values: Use <- or = to assign values to variables.

#For example
x <- 5
y = 10

Printing Values Use the print() function or just type the variable name.

#For example
print(x)
y
[1] 5
10

Arithmetic Operations#

You can perform basic arithmetic operations using the standard operators:

sum <- x + y: Adds x and y, and stores the result in sum. difference <- x - y: Subtracts y from x, and stores the result in difference. product <- x * y: Multiplies x and y, and stores the result in product. quotient <- x / y: Divides x by y, and stores the result in quotient.

#For example
sum <- x + y
difference <- x - y
product <- x * y
quotient <- x / y
print(sum)
print(difference)
print(product)
print(quotient)
[1] 15
[1] -5
[1] 50
[1] 0.5

Logical Operations#

Logical operations compare values and return TRUE or FALSE.

result <- x > y: Checks if x is greater than y. If it is, result will be TRUE; otherwise, it will be FALSE. print(result): Prints the logical result.

#For example
result <- x > y
print(result)
[1] FALSE

Control Structures: if-else Statements#

Control structures like if-else allow you to make decisions based on conditions.

#For example

if (x > y) {
  print("x is greater than y")
} else {
  print("x is not greater than y")
}
[1] "x is not greater than y"

For Loops#

for loops allow you to repeat actions a specific number of times.

#For example

for (i in 1:5) {
  print(i)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

While Loops#

while loops continue to execute as long as a condition is TRUE.

#For example

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

Functions#

Functions allow you to define reusable blocks of code.

#Defining Functions

my_function <- function(a, b) {
  return(a + b)
}

result <- my_function(5, 3)
print(result)
[1] 8