Calculate Ratios Using Base R

We can use the arithmetic operators in Base R, such as division (/) and the round() function, for rounding numerical values. No external packages need to be installed since these functions come by default with R Installation.

Syntax:

data_frame$ratio <- with(data_frame, column1 / column2)

Parameters:

  • data_frame$ratio: This refers to the new column named ratio within the data frame data_frame.
  • <-: The assignment operator; assigns the result of the expression on the right to the object on the left
  • with(data_frame, …): A function that evaluates an expression in the context of a data frame. In this case, it allows us to access columns column1 and column2 directly without repeatedly specifying data_frame$.
  • column1: This refers to the values in the column1 of the data_frame
  • /: The division operator, is used here to divide the values in column1 by values in column2.
  • column2: This refers to the values in the column2 of the data_frame..

Here, We create a dataset “students” with columns: “student_id”, “correct_answers”, and “total_questions_attempted”. We calculate percentages by dividing correct answers by total attempted questions, store results in a “percentage” column, and then round them to two decimal places using round(). The updated dataset is printed.

R




# Sample dataset
students <- data.frame(
  student_id = c(1, 2, 3, 4, 5),
  correct_answers = c(15, 20, 18, 25, 22),
  total_questions_attempted = c(20, 25, 22, 30, 28)
)
 
# Calculate percentage using base R
students$percentage <- students$correct_answers / students$total_questions_attempted * 100
 
# Round percentage to 2 decimal places
students$percentage <- round(students$percentage, 2)
 
# View updated dataset
print(students)


Output:

  student_id correct_answers total_questions_attempted percentage
1 1 15 20 75.00
2 2 20 25 80.00
3 3 18 22 81.82
4 4 25 30 83.33
5 5 22 28 78.57

How to Calculate Ratios in R

Ratios are used to compare quantities by dividing them. They help us to understand how one quantity is related to another quantity. In data analysis, they’re important for understanding proportions. In this article, we will learn How to Calculate Ratios in R Programming Language.

In R programming language we can find ratios by using two methods

  • Using Base R
  • Using dplyr

Similar Reads

Calculate Ratios Using Base R

We can use the arithmetic operators in Base R, such as division (/) and the round() function, for rounding numerical values. No external packages need to be installed since these functions come by default with R Installation....

Using dplyr

...