Professionals in applied statistics are expected to handle, process, and analyze large datasets efficiently. The R programming language, combined with RStudio, is the leading tool for statistical data management in Kenya’s research, government, and business sectors. Mastery of R allows statisticians to sort, merge, aggregate, transform, subset, and export data, core skills for preparing data for analysis and reporting.
2.1 Installing R and RStudio
R is an open-source programming language for statistical computing, while RStudio is a powerful integrated development environment (IDE) that simplifies working with R. Installing both is the first step for any applied statistics professional who wishes to manage data programmatically.
2.1.1 Downloading and Installing R
The process involves downloading the latest version from the Comprehensive R Archive Network (CRAN) and following installation prompts.
Worked Examples
Example 1:
A researcher at a Nairobi hospital wants to install R on a Windows laptop for analyzing patient data.
Given: Internet connection and administrator rights.
- Go to the CRAN website: https://cran.r-project.org
- Click “Download R for Windows.”
- Click “base,” then “Download R 4.x.x for Windows.”
- Run the downloaded installer.
- Accept defaults and complete installation.
- Open R from the Start Menu.
Answer: R is installed and ready to use.
Example 2:
A university lecturer needs R on a Mac for student exam analysis.
Given: Mac OS X computer.
- Visit https://cran.r-project.org
- Click “Download R for macOS.”
- Download the R-x.x.x.pkg file.
- Open the package and follow prompts to install.
- Open R from Applications.
Answer: R is now installed on the Mac.
Example 3:
A county government statistician must install R on Ubuntu Linux.
Given: Ubuntu system.
- Open Terminal.
- Update package lists:
sudo apt-get update
- Install R:
sudo apt-get install r-base
- Confirm installation:
R
- Exit R with
q().
Answer: R is installed on Ubuntu.
2.1.2 Downloading and Installing RStudio
RStudio provides a user-friendly interface for R, making coding, viewing data, and plotting simpler.
Worked Examples
Example 1:
A SACCO data analyst wants RStudio on Windows.
- Go to https://posit.co/download/rstudio-desktop/
- Download the free RStudio Desktop installer for Windows.
- Run the installer and follow prompts.
- Open RStudio from the Start Menu.
Answer: RStudio is installed and ready to use.
Example 2:
A retail business analyst needs RStudio on Mac.
- Visit https://posit.co/download/rstudio-desktop/
- Download the Mac installer.
- Open the .dmg file and drag RStudio to Applications.
- Launch RStudio.
Answer: RStudio is now running on Mac.
Example 3:
A university student in Eldoret wants RStudio on Ubuntu.
- Download the .deb installer from RStudio website.
- Open Terminal and navigate to the download directory.
- Install with:
sudo dpkg -i rstudio-x.yy.zzz-amd64.deb
- Launch RStudio from the Applications menu.
Answer: RStudio is installed on Ubuntu.
2.1.3 Verifying Installation
Testing the installation ensures the environment is ready for data management.
Worked Examples
Example 1:
A researcher opens RStudio and types:
2 + 2
Answer: Output is 4, confirming R works.
Example 2:
A data officer checks the installed version:
version
Answer: R version and platform details are displayed.
Example 3:
A student loads the datasets package:
library(datasets)
Answer: No error, package loads successfully.
Practice Questions
- List the steps to install R on a Windows computer. (3 marks)
- Describe how to verify R is installed correctly using RStudio. (2 marks)
- Outline the procedure to install RStudio on Ubuntu Linux. (3 marks)
The rest of this chapter
🔒Create a free account to open more of this chapter.
Free: practical guides, quick cards, workplace scenarios and more.
Create a free account 🔒2.2 Sorting
Sorting arranges data in ascending or descending order. In R, sorting is crucial for organizing datasets before analysis, such as ranking exam scores or sales figures. The sort() function sorts numeric data in increasing or decreasing order. Example 1: A schoo…
🔒2.3 Merging
Merging combines two or more datasets based on one or more common variables, essential for integrating information from multiple sources. The merge() function joins two data frames using a shared column. Example 1: A hospital merges patient demographic and tes…
🔒2.4 Aggregating
Aggregation summarizes data, such as computing totals, averages, or counts for groups within a dataset. In R, the aggregate() function is commonly used. Summing or averaging values for each group is essential for reporting. Example 1: A retail store sums sales…
🔒2.5 Creating New Variables
Creating new variables adds computed columns to datasets, such as totals, ratios, or categories. Use the $ operator or mutate() to add columns. Example 1: A retail manager wants total price from quantity and unit price. - Formula: ( df$Total = df$Qty times df$…
🔒2.6 Indexing
Indexing selects specific elements, rows, or columns from vectors, matrices, or data frames for analysis or transformation. Use square brackets to select elements by position. Example 1: A SACCO analyst wants the third value from savings: ( x = c(5000, 8000, 1…
🔒2.7 Subsetting
Subsetting extracts portions of data based on positions or conditions, similar to indexing but often returns data frames. Use subset() or logical conditions to select rows. Example 1: A hospital selects patients over 50 years old. - Formula: ( subset(df, Age >…
🔒2.8 Exporting
Exporting saves processed data to files for sharing, reporting, or further analysis. The write.csv() function writes data frames to CSV files. Example 1: A university exports exam results. - Formula: ( text{write.csv}(df, "results.csv", row.names = FALSE) ) -…
🔒2.2 Getting started with R
R is a statistical programming language widely used in Kenya for analyzing data in health, finance, education, and engineering. It allows professionals to efficiently process, visualize, and interpret large datasets. Mastering R is essential for applied statis…
🔒2.3 Data structures in R
R provides several data structures for organizing and manipulating statistical data. Understanding these structures is essential for efficiently storing and processing the different types of data encountered in applied statistics projects. A vector is a sequen…
🔒2.4 Data Entry in R
In applied statistics, efficient data entry and management in R are essential for accurate statistical analysis and reporting. R provides several core data structures for entering, organizing, and manipulating statistical data: arrays, data frames, lists, vect…
🔒2.5 Creating R Projects
R projects are essential for organizing scripts, data, and outputs in applied statistics. They provide a dedicated workspace, helping professionals in Kenya manage statistical data efficiently and avoid confusion between files. The structure of an R project en…
🔒2.6 Importing Data into R
CSV files are commonly used in applied statistics for storing tabular data. R provides functions like read.csv() to import these files for analysis. $$ text{data} = text{read.csv}(text{"file.csv"}) $$ Example 1: A bank analyst imports transaction data from "tr…
🔒2.7 Installing R Packages
Installing R packages is an essential skill for applied statistics professionals, as packages extend R’s core functionality with specialized statistical tools. In Kenya, analysts routinely install packages such as tidyverse, ggplot2, and readxl to handle data…
🔒2.8 Data Manipulation in R
Data manipulation in R is the process of cleaning, transforming, and organizing raw data into an analyzable format. Applied statistics professionals in Kenya use data manipulation to prepare health records, financial transactions, and survey results for statis…
🔒2.10 Descriptive Statistics
Descriptive statistics are vital for applied statistics professionals in Kenya, enabling clear summarization and interpretation of raw data collected in fields like health, agriculture, finance, and education. Using R, these statistics allow practitioners to a…
🔒2.11 Statistical Inference
Statistical inference is the process of making predictions or decisions about a population based on sample data. In applied statistics, professionals use inference to estimate population parameters, test hypotheses, and draw conclusions from survey or experime…
🔒2.12 Regression Analysis
Regression analysis is a statistical technique for modeling the relationship between a dependent variable and one or more independent variables. In applied statistics, regression is used to predict outcomes, assess trends, and support planning decisions in sec…
🔒2.13 Time Series Analysis in R
Time series analysis is essential in applied statistics for understanding data collected over time, such as rainfall measurements, electricity consumption, or stock prices. R provides a robust environment for time series manipulation, visualization, and foreca…
🔒2.14 Probability Distribution in R
Probability distributions describe the likelihood of different outcomes in statistical experiments. In R, functions are available to generate, visualize, and analyze both discrete and continuous distributions. Applied statisticians in Kenya use probability dis…
🔒2.15 Random numbers
Random numbers are used in applied statistics to simulate sampling, generate random datasets, and perform Monte Carlo methods. R provides functions to generate random numbers from various distributions, which is essential for statistical modeling, hypothesis t…
🔒2.16 R Commander
R Commander is a graphical user interface (GUI) for R, designed to make statistical analysis accessible to users who prefer point-and-click operations over scripting. It is widely used in Kenyan applied statistics settings for data entry, manipulation, visuali…
🔒2.17 Built-in functions in R
R is a powerful statistical programming language widely used by applied statistics professionals in Kenya for data handling, analysis, and reporting. Built-in functions in R allow users to quickly perform calculations, summarize data, and generate statistical…
Chapter Summary
This chapter introduced the process of installing R and R Studio, providing the foundation for statistical computing and analysis. Learners explored the basics of getting started with R, including understanding its interface and commands. The chapter covered essential data structures such as arrays, data frames, lists, vectors, and matrices, and demonstrated various methods for data entry in R. Steps for creating R projects and importing data from different sources were explained, followed by guidance on installing and managing R packages. Data manipulation techniques such as sorting, merging, aggregating, creating new variables, indexing, subsetting, and exporting were thoroughly discussed. The chapter also examined graphical methods for data visualization, including scatter plots, line graphs, histograms, density plots, pie charts, bar charts, and box plots. Key concepts in descriptive statistics, statistical inference, regression analysis, time series analysis, probability distributions, and generating random numbers were addressed. Finally, the use of R Commander and built-in R functions was highlighted to enhance efficiency in managing and analyzing statistical data.
Self-Assessment
🔒 PDFDownload this self-assessment, with answers
Written Assessment
- A retail chain collects weekly sales data for 5 branches over 4 weeks. Enter this data as a matrix in R and calculate the total sales for each branch. (4 marks)
Show Worked Solutions
Given:
Branch sales (in Ksh thousands):
Week 1: 12, 15, 14, 10, 16
Week 2: 13, 16, 15, 11, 17
Week 3: 14, 17, 13, 12, 18
Week 4: 15, 18, 16, 13, 19
Step 1: Create the matrix in R:
sales_matrix <- matrix(c(12,15,14,10,16,13,16,15,11,17,14,17,13,12,18,15,18,16,13,19), nrow=4, byrow=TRUE)
Step 2: Calculate branch totals (column sums):
branch_totals <- colSums(sales_matrix)
$$
\text{Branch 1: } 12 + 13 + 14 + 15 = 54
$$$$
\text{Branch 2: } 15 + 16 + 17 + 18 = 66
$$$$
\text{Branch 3: } 14 + 15 + 13 + 16 = 58
$$$$
\text{Branch 4: } 10 + 11 + 12 + 13 = 46
$$$$
\text{Branch 5: } 16 + 17 + 18 + 19 = 70
$$
Final answers:
Branch totals: 54 Ksh, 66 Ksh, 58 Ksh, 46 Ksh, 70 Ksh (thousands)
- Import the following CSV data into R and calculate the mean value for the variable "income":
income: 25000, 30000, 15000, 40000, 20000 (3 marks)
Show Worked Solutions
Step 1: Import data
income <- c(25000, 30000, 15000, 40000, 20000)
Step 2: Calculate mean$$
\text{Mean} = \frac{25000 + 30000 + 15000 + 40000 + 20000}{5}
$$$$
= \frac{130000}{5}
$$$$
= 26000
$$
Final answer:
26,000 Ksh
🔒8 more in this section.
Chapter Examination Questions
🔒 PDFDownload these examination questions, with worked answers
SECTION A (40 Marks) - Answer ALL Questions
-
A data analyst at the Kenya National Bureau of Statistics (KNBS) is tasked with summarizing the monthly inflation rates. Describe the steps required to import an Excel file containing the rates into R, and write the R code to display the first six rows of the data. (4 marks)
-
Differentiate between a vector and a data frame in R, and provide an example of each using agricultural yield data from a county in Kenya. (4 marks)
🔒18 more in this section.