Learn R – Part 1

R uses simple syntax to execute commands. Code is written line-by-line, and print() or cat() displays output. Try, if you can solve the below problem.

# HW 1: Print "Hello, R!"  

# HW 2: Calculate 5 + 3 and print the result  
R
print("Hello, R!")  
cat("Result:", 5 + 3)  

Use class() / typeof() to check the data type of a variable (e.g., numeric, character).

# HW 1: Check the type of "apple"  

# HW 2: Check the type of 25.6  
R
class("apple")  # Output: "character"  
typeof(25.6)     # Output: "double"  

Use as. function to set forcefully a data type like as.numeric() or as.character().

# HW 1: Convert "100" to numeric  

# HW 2: Convert 50 to character  
R
as.numeric("100")  # Output: 100  
as.character(50)   # Output: "50"  

Use vectors (created with c()) to store multiple values of the same type.

# HW 1: Create a vector of numbers 1, 2, 3  

# HW 2: Create a vector of colors: "red", "blue"  
R
nums <- c(1, 2, 3)  
colors <- c("red", "blue")  

Assign values to variables using <- or =. Example: x <- 10.

# HW 1: Assign 3.14 to "pi"  

# HW 2: Assign "Rocks" to "language"  
R
pi <- 3.14  
language <- "Rocks"  

Use # to add comments (notes) to your code. R ignores these lines.

# HW 1: Write a comment explaining the next line  

  print("Learning R!")  
R
# This line prints a motivational message  
print("Learning R!")  

Variables in R store data, and their type is automatically inferred from the assigned value. Use <- or = to assign values. Example: x <- 10 (numeric), y <- "Hello" (character).

# HW1: Assign 3.14 to a variable  
# HW2: Assign "R Programming" to a variable  

# HW3: Assign TRUE to a variable  
R
pi_value <- 3.14  
language <- "R Programming"  
is_fun <- TRUE  

R supports numeric (e.g., 10.5), integer (e.g., 55L), complex (e.g., 9+3i), character (e.g., "R is exciting"), and logical (e.g., TRUE). Use class() to check the type.

# HW1: Create a numeric variable with 787  
# HW2: Create an integer with 100L  
# HW3: Create a complex number 9+3i  
# HW4: Create a character "FALSE"  

# HW5: Create a logical FALSE  
R
num <- 787  
integer_val <- 100L  
complex_num <- 9 + 3i  
char <- "FALSE"  
logical_val <- FALSE  

R has built-in functions for math operations:

min(): Finds the smallest value.

floor(): Rounds down to the nearest integer.

max(): Finds the largest value.

sqrt(): Calculates the square root.

abs(): Returns absolute value.

ceiling(): Rounds up to the nearest integer.

# HW1: Find the minimum of 10, 20, 5  
# HW2: Calculate the square root of 16  
# HW3: Round 3.2 up and 4.9 down  

# HW4: Get the absolute value of -7.5  
R
min_val <- min(10, 20, 5)  # Output: 5  
sqrt_val <- sqrt(16)       # Output: 4  
ceil_val <- ceiling(3.2)   # Output: 4  
floor_val <- floor(4.9)    # Output: 4  
abs_val <- abs(-7.5)       # Output: 7.5  

Booleans are TRUE or FALSE. Use logical operators like & (AND), | (OR), and ! (NOT) to combine conditions.

# HW1: Check if 5 > 3 AND 2 < 4 
# HW2: Check if 10 == 10 OR 7 != 7  

# HW3: Reverse the value of TRUE  
R
bool1 <- (5 > 3) & (2 < 4)
bool1   # Output: TRUE  
bool2 <- (10 == 10) | (7 != 7)
bool2   # Output: TRUE  
bool3 <- !TRUE  
bool3   # Output: FALSE  

Used for basic math operations: + (add), - (subtract), * (multiply), / (divide), ^ (exponent), %% (modulus).

# HW1: Calculate 10 + 5  
# HW2: Calculate 10 - 5  
# HW3: Calculate 4 * 6  
# HW4: Calculate 20 / 4  
# HW5: Calculate 3^2 (3 squared)  

# HW6: Find the remainder of 10 %% 3  
R
add <- 10 + 5   # 15  
sub <- 10 - 5   # 5  
mul <- 4 * 6    # 24  
div <- 20 / 4   # 5  
exp <- 3^2      # 9  
mod <- 10 %% 3  # 1  

Assign values to variables: <-, =, or -> (rarely used). Example: x <- 5 or 5 -> x.

# HW1: Assign 10 to `a` using `<-`  
# HW2: Assign 20 to `b` using `=`  

# HW3: Assign 30 to `c` using `->`  
R
a <- 10  
b = 20  
30 -> c  

Compare values: == (equal), != (not equal), >, <, >=, <=. Returns TRUE or FALSE.

# HW1: Check if 5 == 5  
# HW2: Check if 10 != 5  
# HW3: Check if 8 > 3  

# HW4: Check if 4 <= 4  
R
5 == 5    # TRUE  
10 != 5  # TRUE  
8 > 3     # TRUE  
4 <= 4   # TRUE  

Combine conditions: & (AND), | (OR), ! (NOT).

# HW1: Check if (5 > 3) & (2 < 4)  
# HW2: Check if (10 == 5) | (3 != 3)  

# HW3: Reverse the result of TRUE using `!`  
R
(5 > 3) & (2 < 4)  # TRUE  
(10 == 5) | (3 != 3)  # FALSE  
not_op <- !TRUE  
not_op    # FALSE  

Use if to execute code if a condition is TRUE, and else for when it’s FALSE.

# HW1: Check if 10 is greater than 5, print "Yes"  
# HW2: Check if 7 is even; if not, print "Odd"  

# HW3: Assign "Pass" if score >= 50, else "Fail"  
R
# HW1  
if (10 > 5) {  
  print("Yes")  
}  

# HW2  
if (7 %% 2 == 0) {  
  print("Even")  
} else {  
  print("Odd")  
}  

# HW3  
score <- 55  
result <- if (score >= 50) "Pass" else "Fail"  
print(result)  

Repeats code while a condition is TRUE. Use break to exit early.

# HW1: Print numbers 1 to 5  

# HW2: Sum numbers from 1 to 3  
R
# HW1  
i <- 1  
while (i <= 5) {  
  print(i)  
  i <- i + 1  
}  

# HW2  
total <- 0  
j <- 1  
while (j <= 3) {  
  total <- total + j  
  j <- j + 1  
}  
print(total)  # Output: 6  

Iterates over a sequence (like a vector). Use break/next to control flow.

# HW1: Print numbers 1 to 3 from c(1, 2, 3)  
# HW2: Calculate sum of 1, 2, 3 using a loop  

# HW3: Loop through a matrix (2x2) and print values  
R
# HW1  
for (num in c(1, 2, 3)) {  
  print(num)  
}  

# HW2  
sum <- 0  
for (i in 1:3) {  
  sum <- sum + i  
}  
print(sum)  # Output: 6  

# HW3  
mat <- matrix(1:4, nrow=2)  
for (row in 1:nrow(mat)) {  
  for (col in 1:ncol(mat)) {  
    print(mat[row, col])  
  }  
}  

Reusable code blocks. Use function() to define, and return() to output results.

# HW1: Create a function to square a number  

# HW2: Create a function that says "Hello, [name]!"  
R
# HW1  
square <- function(x) {  
  return(x^2)  
}  
print(square(4))  # Output: 16  

# HW2  
greet <- function(name) {  
  return(paste("Hello,", name, "!"))  
}  
print(greet("Alice"))  # Output: "Hello, Alice!"  

Leave a Reply

Your email address will not be published. Required fields are marked *