Summary Statistics in R

In this article, you will learn about how to perform Summary Statistics in R Language on a data set and finally, you will create a data quality Report file. Let us start learning “Computing Summary Statistics in R”.

We will follow each step as a Task for better understanding. It will also help us to complete all work in sequential tasks.

Task 1: Load and View Data Set

It is better to confirm the working directory using getwd() and save your data in the working directory, or save the data in the required folder and then set the path of this folder (directory) in R using setwd() function.

getwd()
data <- read.csv("data.csv")

Task 2: Calculate Measure of Frequency Metrics in R

Before calculating the frequency metrics it is better to check the data structure and some other useful information about the data, For example,

Note: here we are using mtcars data set.

data <- mtcars
str(data)
head(data)
length(data$cyl)
length(unique(data$cyl))
table(data$cyl)

freq <- table(data$cyl)
freq <- sort(freq, descreasing = T)
print(freq)
Descriptive summary Statistics in R

The above lines of code will tell you about the number of observations in the data set, the frequency of the cylinder variable, its unique category, and finally sorted frequency in order.

Task 3: Calculate the Measure of Central Tendency in R

Here we will calculate some available measures of central tendencies such as mean, median, and mode. One can easily calculate the measures of central tendency in R by following the commands below:

mean(data$mpg)
mean(data$mpg, na.rm = T)
median(data$mpg)
median(data$mpg, na.rm = T)

Note the use of na.rm argument. If there are missing values in the data then na.rm should be set to true. Since the mtcars data set does not contain any missing values, therefore, results for both will be the same.

There is no direct function to compute the most repeated value in the variable. However, using a combination of different functions we can calculate the mode. For example

# for continuous variable
uniquevalues <- unique(data$hp)
uniquevalues[which.max(tabulate(match(data$ho, uniquevalues)))]
# for categorical variable
uniquevalues <- unique(data$cyl)
uniquevalues[which.max(tabulate(match(data$cyl, uniquevalues)))]

Task 4: Calculate Measure of Dispersion in R Programming

The measures of dispersion such as range, variance, and standard deviation can be computed as given below. The use of different functions for the measure of dispersion in R programming is described as follows:

min(data$disp)
min(data$disp, na.rm = T)
max(data$disp)
max(data$disp, na.rm = T)
range(data$disp, na.rm = T)
var(data$disp, na.rm = T)
sd(data$disp, na.rm = T)

Task 5: Calculate Additional Quality Data Metrics

To compute more data metrics we must be aware of the data type of variables. Suppose we have numbers but its data type is set to the character. For example,

test <- as.character(1:3)

Finding the mean of such character variable (the numbers are converted to character class) will result in a warning.

mean(test)

[1] NA 
Warning message: In mean.default(test) : argument is not numeric or logical: returning NA

Therefore, one must be aware of the data type and class of the variable for which calculations are being performed. The class of variable in R can be checked using class() function. For example

class(data$hp)
class(mtcars)

It may also be useful if we know the number of missing observations in the data set.

test2 <- c(NA, 2, 55, 10, NA)

sum(is.na(test2))
sum(is.na(data$hp))
sum(is.na(data$hp))

Note that the data set we are using does not contain any missing values.

Task 6: Computing Summary Statistics in R on all Columns

There are functions in R that can be applied to each column to perform certain calculations on them. For example, apply() the function is used to compute the number of observations in the data set using length function as an argument of apply() function.

apply(data, MARGIN=2, length)

sapply(data, function(x) min(x, na.rm=T))

Let us create a user-defined function that can compute the minimum, maximum, mean, total, number of missing values, unique values, and data type of each variable (column) of the data frame.

quality_data <- function(df = NULL){
    if (is.null(df))
          print("Please Pass a non-empty data frame")
  
summary_tab <- do.call(data.frame,
     list(
           Min = sapply(df, function(x) min(x, na.rm = T) ),
           Max = sapply(df, function(x) max(x, na.rm = T) ),
           Mean = sapply(df, function(x) mean(x, na.rm = T) ),
           Total = apply(df, 2, length),
           NULLS = sapply(df, function(x) sum(is.na(x)) ),
           Unique = sapply(df, function(x) length(unique(x)) ),
           DataType = sapply(df, class)
      )
)
                         
nums <- vapply(summary_tab, is.numeric, FUN.VALUE = logical(1))
summary_tab[, nums] &lt;- round(summary_tab[, nums], digits = 3)
      
return(summary_tab)

}

quality_data(data)

Task 7: Generate a Quality Data Report File

df_quality <- quality_data(data)
df_quality <- cbind(columns = rownames(df_quality),
                    data.frame(df_quality, row.names = NULL)  )

write.csv(df_quality, "Data Quality Report.csv", row.names = F)

write.csv(df_quality, paste0("Data Quality Repor", 
      format(Sys.time(), "%d-%m-%Y-%M%M%S"), ".csv"),
      row.names = F)

The write.csv() function will create a file that contains all the results produced by the quality_data() function.

That’s all about Calculating Descriptive Statistics in R. There are many other descriptive measures, we will learn in future posts.

To learn about importing and exporting different data files, see the post on Importing and Exporting Data in R.

FAQs in R

  1. What summary statistics can easily be computed in R?
  2. How to load the data set in the current workspace?
  3. What are the functions that can be used to compute different measures of dispersions in R Language?
  4. How to compute the summary statistics of all columns at once in R?
  5. What measure of central tendencies can be computed in R?
  6. What functions can be used to get information about the loaded dataset in R?
  7. How missing observations can be identified in R?

Learn Basic Statistics

Scatter Plots In R

Introduction to Scatter Plots in R Language

Scatter plots (scatter diagrams) are bivariate graphical representations for examining the relationship between two quantitative variables. Scatter plots are essential for visualizing correlations and trends in data. A scatter plot helps identify the direction and strength of the relationship between two quantitative variables. The scatter plot also helps in identifying the linear to non-linear trend in the data. If there are more than two variables in a data set, one can draw a scatter matrix diagram between all/different pairs of quantitative variables.

Scatter plots in R can be drawn in several ways. Here, we will discuss how to make several kinds of scatter plots in R.

The plot Function in R

For plot() function in R, when two numeric vectors are provided as arguments (one for horizontal and the other for vertical coordinates), the default behavior of the plot() function in R is to make a scatter diagram. For example,

library(car)
attach(Prestige)
plot(income, prestige)

will draw a simple scatterplot of prestige by income.

Usually, the interpretation of a scatterplot is often assisted by enhancing the plot with least-squares or non-parametric regression lines. For this purpose scatterplot() in car package can be used, and it will add marginal boxplots for the two variables

scatterplot(prestige ~ income, lwd = 3 )

Note that in the scatterplot, the non-parametric regression curve is drawn by a local regression smoother, where local regression works by fitting a least-square line in the neighborhood of each observation, placing greater weight on points closer to the focal observation. A fitted value for the focal observation is extracted from each local regression, and the resulting fitted values are connected to produce the non-parametric regression line.

Coded Scatterplots

The scatterplot() function can also be used to create coded scatterplots. For this purpose, a categorical variable is used for coloring or using different symbols for each category. For example, let us plot prestige by income, coded by the type of occupation

scatterplot(prestige ~ income | type)

Note that variables in the scatterplot are given in a formula-style (as y ~ x | groups).

The coded scatterplot indicates that the relationship between prestige and income may well be linear within occupation types. The slope of the relationship looks steepest for blue-collar (bc) occupations and least steep for professional and managerial occupations.

Common Plot Symbols in R

R uses numeric values to represent different symbols. The following is a list of the most commonly used plot symbols and their corresponding numbers:

SymbolCodeDescription
Circle1Solid circle (default)
Square15Solid square
Triangle2Solid triangle
Diamond18Solid diamond
Plus Sign3Plus sign
X4X marks the spot
Open Circle1Circle with no fill
Open Square0Square with no fill
Open Triangle17Triangle with no fill

Customizing Your Scatter Plots in R

One can customize the scatter plot further by adjusting the point size, color, axis labels, title, and more. For example, customized Scatter Plot with Larger Points and Color:

# Customized scatter plot
plot(x, y, 
     main="Customized Scatter Plot", 
     xlab="X Axis Label", ylab="Y Axis Label", 
     pch=17, col="red", cex=1.5, 
     xlim=c(0, 6), ylim=c(0, 12))
  • pch=17: Uses a triangle symbol for points.
  • col="red": Changes the point color to red.
  • cex=1.5: Increases the point size.
  • xlim=c(0, 6) and ylim=c(0, 12): Sets the x and y axis limits.

Jittering Scatter Plots

Jittering the data by adding a small random quantity to each coordinate serves to separate the overplotted points.

data(Vocab)
attach(Vocab)
plot(education, vocabulary) 
# without jittering
plot(jitter (education), jitter(vocabulary) )
Scatter Plots in R Language

The degree of jittering can be controlled via a factor argument. For example, specifying factor = 2 doubles the jitter.

plot(jitter(education, factor = 2), jitter(vocabulary, factor = 2))

Let’s add the least-squares and non-parametric regression line.

abline(lm(vocabulary ~ education), lwd = 3, lty = 2)
lines(lowess(education, vocabulary, f = 0.2), lwd = 3)

The lowess function (an acronym for locally weighted regression) returns coordinates for the local regression curve, which is drawn by lines. The “f” arguments set the span of the local regression to lowess.

Using these different kinds of graphical representations of relationships between variables may help to identify some hidden information (hidden due to overplotting).

FAQs about Scatter Plots in R

  1. How can one draw a scatter plot in R Language?
  2. What is the importance of scatter plots?
  3. What function can be used to draw scatter plots in R?
  4. What is the use of the scatterplot() function in R?
  5. What is meant by a coded scatter plot?
  6. What are jittering scatter plots in R?
  7. What are the important arguments of a plot() function to draw a scatter plot?
  8. What is meant by R Plot Symbols?

See more on plot() function

Summary

Scatter plots in R are essential for visualizing relationships between two continuous variables, detecting patterns, and identifying trends. You can customize the points, colors, add regression lines, and even incorporate grids for clearer insights.

https://itfeature.com, https://gmstat.com

Important MCQs R Language History & Basics 4

The post is about MCQs R Language. The quiz about MCQS R Language covers some basics of R language, its functionality, concepts of packages, and history of R Language.

MCQs about R Language

1. The following packages are not contained in the “base” R system.

 
 
 
 

2. The wrong statement from the following is:

 
 
 
 

3. Which package contains most fundamental functions to run R?

 
 
 
 

4. R functionality is divided into a number of _______

 
 
 
 

5. R is published under the ______ General Public License version.

 
 
 
 

6. Which of the following is the wrong statement:

 
 
 
 

7. The primary source code copyright for R is held by the

 
 
 
 

8. In which year the R-Core Team was formed?

 
 
 
 

9. What is the output of getOption(“defaultPackages”) in R Studio?

 
 
 
 

10. One limitation of R is that its functionality is based on _________

 
 
 
 

11. which of the following is a “base” package for R language?

 
 
 
 

12. R Runs on the _________ operating system

 
 
 
 

13. The primary R system is available from the ______

 
 
 
 

14. Which of the following is used for Statistical analysis in the R language?

 
 
 
 

15. The public version of R released in 2000 was

 
 
 
 

16. Which of the following is a recommended package in R

 
 
 
 

17. Advanced users of R can write _______ code to manipulate R objects directly

 
 
 
 

18. The “base” R system can be downloaded from

 
 
 
 

19. Which of the following are best practices for creating data frames?

 
 
 
 

20. Which of the following are examples of variable names that can be used in R?

 
 
 
 

The R language is a free and open-source language developed by Ross Ihaka and Robert Gentleman in 1991 at the University of Auckland, New Zealand. The R Language is used for statistical computing and graphics to clean, analyze, and graph your data.

MCQs R Language History and Basics

MCQs R Language History and Basics Online Quiz

  • In which year the R-Core Team was formed?
  • The public version of R released in 2000 was
  • R Runs on the operating system
  • The primary source code copyright for R is held by the
  • R is published under the General Public License version.
  • The “base” R system can be downloaded from
  • The following packages are not contained in the “base” R system.
  • One limitation of R is that its functionality is based on __________.
  • The wrong statement from the following is:
  • R functionality is divided into a number of
  • The primary R system is available from the ________.
  • Which package contains the most fundamental functions to run R?
  • Which of the following is the wrong statement:
  • Which of the following is a “base” package for the R language?
  • Which of the following is a recommended package in R
  • What is the output of getOption(“defaultPackages”) in R Studio?
  • Advanced users of R can write ___________ code to manipulate R objects directly
  • Which of the following is used for Statistical analysis in the R language?
  • Which of the following are examples of variable names that can be used in R?
  • Which of the following are best practices for creating data frames?

The strengths of R programming language lie in its statistical capabilities, data visualization tools (such as ggplot2), and a vast ecosystem of packages contributed by the community. R Language remains a popular choice for statisticians and data scientists working on a wide range of projects.

Basic Statistics and Data Analysis