Extract Numerator & Denominator of Fraction in R (Example)
In this R programming tutorial, you’ll learn how to extract numerators and denominators of fractions.
The tutorial is structured as follows:
Let’s take a look at some R codes in action.
Before all else, we have to define some data that we can use in the examples below.
fractions <- c("5/3", "6/4", "7/2") # define fraction vector
As seen, we defined a vector of fractions called
In the following example, we will see how to extract the numerators and denominators of the given fractions.
Example: Get Numerator & Denominator of Fractions
In this example, we will use the strplit() function, which splits the elements of a string vector into substrings according to the matching substring. In our case, this substring is the slash symbol
split_fract <- strsplit(fractions, "/") # split fraction into two parts split_fract # [] #  "5" "3" # [] #  "6" "4" # [] #  "7" "2"
The previous output of the RStudio console shows that
strsplit() split the fractions into parts of numerators and denominators. All split fractions are stored in a separate vector within the output list
In order to extract the numerators, we should retrieve the first elements of these vectors. Let’s see how it is done!
num<- as.integer(sapply(split_fractions, "[", 1)) # extract numerators num # print numerators #  5 6 7
In the script above,
"[" is the indexing function, which access to the indexes of a list or a vector.
1 is the parameter indicating which index will be accessed.
The sapply() function is employed to apply this indexing function to each vector of the
split_fract list. Next, we will extract the denominator in a similar manner.
denom <- as.integer(sapply(split_fractions, "[", 2)) # extract denominators denom # print denominators #  3 4 2
As promised, all denominators are extracted calling the second index of the vectors of
Video, Further Resources & Summary
Do you want to know more about the extraction of numerator and denominators? Then you may want to have a look at the following video on my YouTube channel. I’m explaining the R code of this tutorial in the video.
The YouTube video will be added soon.
In addition, you might read the other tutorials on www.statisticsglobe.com.
- Introduction to R
- Convert Decimals to Reduced Fractions in R
- Convert Fraction to Decimal in R
- apply Functions in R
Summary: In this article, I have demonstrated how to get numerators and denominators in R programming. Let me know in the comments, in case you have further questions.
This page was created in collaboration with Cansu Kebabci. Have a look at Cansu’s author page to get more information about her professional background, a list of all his tutorials, as well as an overview on her other tasks on Statistics Globe.
Statistics Globe Newsletter