![]() |
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
Calculate Ratios Using Base RWe 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:
Parameters:
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
Output: student_id correct_answers total_questions_attempted percentage Using dplyrWe utilize the dplyr package for its data manipulation features, including the mutate() function. This function helps us in creating new columns in data frames. The calculated ratios are along with the original data in a new column. This improves data organization and analysis. Since dplyr extends data manipulation capabilities, we need to install external packages. mutate() FunctionThe mutate() function is a part of the dplyr package in the R programming language. It is a powerful data manipulation tool. The mutate() function creates new columns within your data frame. It allows you to apply various transformations and calculations to existing data. Syntax:
Parameters:
Now calculate the ratiosHere, We create a dataset “monthly_finances” containing months, revenue, and expenses. Using dplyr, we calculate profit margins by subtracting expenses from revenue and dividing by revenue. The updated dataset is then printed to display the new “profit_margin” column. R
Output: month revenue expenses profit_margin ConclusionIn conclusion, calculating ratios in R is important for comparing and interpreting quantities in data analysis. In this article, We learned two methods: base R operations and the dplyr package for Calculating Ratios in R. |
Reffered: https://www.geeksforgeeks.org
Dev Scripter |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |