Basic Operations in R Programming


1. Arithmetic Operations

R supports basic arithmetic operations such as addition, subtraction, multiplication, and division.

    # Addition
    result_add <- 10 + 5
    print(result_add)
    
    # Subtraction
    result_sub <- 10 - 5
    print(result_sub)
    
    # Multiplication
    result_mul <- 10 * 5
    print(result_mul)
    
    # Division
    result_div <- 10 / 5
    print(result_div)
    
    # Modulus (remainder)
    result_mod <- 10 %% 3
    print(result_mod)
    
    # Exponentiation
    result_exp <- 2^3
    print(result_exp)
        

2. Logical Operators

Logical operators are used for comparisons and logical operations.

    # Equality
    is_equal <- (10 == 5)
    print(is_equal)
    
    # Inequality
    is_not_equal <- (10 != 5)
    print(is_not_equal)
    
    # Greater than
    is_greater <- (10 > 5)
    print(is_greater)
    
    # Less than
    is_less <- (10 < 5)
    print(is_less)
    
    # Logical AND
    logical_and <- (TRUE & FALSE)
    print(logical_and)
    
    # Logical OR
    logical_or <- (TRUE | FALSE)
    print(logical_or)
        

3. Basic Functions

3.1 print()

The print() function is used to display output in the console.

    # Printing a message
    print("Hello, R Programming!")
        

3.2 c()

The c() function is used to combine values into a vector.

    # Creating a vector using c()
    my_vector <- c(1, 2, 3, 4, 5)
    print(my_vector)
        

3.3 mean()

The mean() function calculates the average of a numeric vector.

    # Calculating the mean
    my_numbers <- c(10, 20, 30, 40, 50)
    result_mean <- mean(my_numbers)
    print(result_mean)
        

3.4 sum()

The sum() function calculates the total of a numeric vector.

    # Calculating the sum
    my_numbers <- c(10, 20, 30, 40, 50)
    result_sum <- sum(my_numbers)
    print(result_sum)
        

Conclusion

This tutorial covered basic operations in R, including arithmetic, logical operators, and fundamental functions such as print(), c(), mean(), and sum(). These are essential for performing calculations and handling data in R programming.





Advertisement