[R] Calculation

This post covers how to perform calculations in R Studio.

    1. Preparation

    First, note that string variables are unable to compute.

    Also, only variables that have the same cases of value can be computed.

    Before any computation, let's make a couple of variables as follows.

    If you do not know how to generate variables, refer to the link below.

    https://ik-lab.blogspot.com/2022/06/r-studio-variable-generation.html

    As long as the variables are not string variables, they can be computed with arithmetic operations as follows.

    #preparation
    a <- c(1:5)
    b <- c(2:6)
    a
    b
    
    #Console window
    > a
    [1] 1 2 3 4 5
    > b
    [1] 2 3 4 5 6
    

    2. Addition

    For addition, '+' is used.

    #Addition
    a+1
    a+b
    
    #Console window
    > a+1
    [1] 2 3 4 5 6
    > a+b
    [1]  3  5  7  9 11
    

    3. Subtraction

    For subtraction, '-' is used.

    #Subtraction
    a-1
    a-b
    
    #Console window
    > a-1
    [1] 0 1 2 3 4
    > a-b
    [1] -1 -1 -1 -1 -1
    

    4. Multiplication

    For multiplication, '*' is used.

    #Multiplication
    2*a
    a*2
    a*b
    
    #Console window
    > 2*a
    [1]  2  4  6  8 10
    > a*2
    [1]  2  4  6  8 10
    > a*b
    [1]  2  6 12 20 30
    

    5. Division

    For division, '/' is used.

    #Division
    4/a
    a/4
    a/b
    
    #Console window
    > 4/a
    [1] 4.000000 2.000000 1.333333 1.000000 0.800000
    > a/4
    [1] 0.25 0.50 0.75 1.00 1.25
    > a/b
    [1] 0.5000000 0.6666667 0.7500000 0.8000000 0.8333333
    

    6. Factorial

    For factorial, factorial() function is used.

    #Factorial
    factorial(4)
    factorial(a)
    
    #Console window
    > factorial(4)
    [1] 24
    > factorial(a)
    [1]   1   2   6  24 120
    

    7. Square root

    For square roots, sqrt() function is used.

    #Square root
    sqrt(16)
    sqrt(a)
    
    #Console window
    > sqrt(16)
    [1] 4
    > sqrt(a)
    [1] 1.000000 1.414214 1.732051 2.000000 2.236068
    

    Post a Comment

    0 Comments