There are two different ways to calculate ratios in R.

The following methods show how you can do it with syntax.

Method 1: Use Base R

ratio <- column1/column2

Method 2: Use dplyr Package

library(dplyr)

 df %>%
        mutate(ratio = column1/column2)

The following examples show how to calculate ratio in R.

Calculate Ratios in R Using Base R

Let’s see how we can calculate ratio in R:

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","A","B","C","D"),
                 Pressure=c(78.2, 78.2, 71.7, 80.21, 80.21, 82.56, 72.12, 73.85),
                 Temperature=c(35, 36, 36, 38, 32, 32, 31, 34))

# Calculate ratio between Pressure and Temperature
df$ratio <-  round(df$Pressure/df$Temperature, 3)

# Print data frame
print(df)

Output:

 Machine_name Pressure Temperature ratio
1            A    78.20          35 2.234
2            B    78.20          36 2.172
3            C    71.70          36 1.992
4            D    80.21          38 2.111
5            A    80.21          32 2.507
6            B    82.56          32 2.580
7            C    72.12          31 2.326
8            D    73.85          34 2.172

As the output shows ratio between Pressure and Temperature column of data frame. Also here we use round() function to round off upto 3 decimal values.

Calculate Ratios in R Using dplyr Package

Let’s see how we can use functions from dplyr package in R:

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","A","B","C","D"),
                 Pressure=c(78.2, 78.2, 71.7, 80.21, 80.21, 82.56, 72.12, 73.85),
                 Temperature=c(35, 36, 36, 38, 32, 32, 31, 34))

# Calculate ratio between Pressure and Temperature
df$ratio <- df %>%
        mutate(ratio = Pressure/Temperature)

# Print data frame
print(df)

Output:

 Machine_name Pressure Temperature ratio.Machine_name ratio.Pressure ratio.Temperature
1            A    78.20          35                  A          78.20                35
2            B    78.20          36                  B          78.20                36
3            C    71.70          36                  C          71.70                36
4            D    80.21          38                  D          80.21                38
5            A    80.21          32                  A          80.21                32
6            B    82.56          32                  B          82.56                32
7            C    72.12          31                  C          72.12                31
8            D    73.85          34                  D          73.85                34
  ratio.ratio
1    2.234286
2    2.172222
3    1.991667
4    2.110789
5    2.506562
6    2.580000
7    2.326452
8    2.172059

As the output shows ratio for each column of data frame which calculated using functions from dplyr package.