Work with simple data using 5 functions from dplyr: A beginner's guide to using dplyr, with examples of working with HR data

  1. 💻 R language
  2. 🔢 dplyr: A library for manipulating data
  3. 🧑‍💼 HR Data Example
  4. ✍️ Function Writing Pattern
  5. 1️⃣ Function #1: select()
  6. 2️⃣ Function #2: filter()
  7. 3️⃣ Function #3: arrange()
  8. 4️⃣ Function #4: summarize()
  9. 5️⃣ Function #5: mutate()
  10. 🫂 Putting Everything Together: Pipe Operator
  11. 🔥 Summary of 5 Functions from dplyr
  12. Try it yourself!
  13. 📚 Read more about dplyr
  14. ✅ R Book for Psychologists: An R Book for Psychologists

💻 R language

R is a computer language designed to work with data. It is suitable for professions that involve working with data, such as:

  • Researchers who want to analyze the characteristics of a sample group, such as the number of samples by gender or age group
  • Data analysts who want to gain insights from organizational data, such as analyzing business trends
  • Sales: For those who want to analyze sales data, such as the number of customers, sales, and profits
  • Or even HR who wants to work with employee data, such as analyzing performance, engagement, and job satisfaction

🔢 dplyr: A library for manipulating data

R Has Built-in functions and libraries A variety of libraries that support working with data in different formats, one of the most popular libraries being dplyr

dplyr It is a library designed to Data transformation Or data transformation makes working with data easier compared to built-in functions.

Use case of dplyr E.g.:

  • Data exploration
  • Data cleaning
  • Data analysis

.

In this article, we will get to know 5 functions The basics of dplyr used to work with data, including:

  1. select()
  2. filter()
  3. arrange()
  4. summarise() OR summarize() (Both forms are acceptable.)
  5. mutate()

🧑‍💼 HR Data Example

In this article, we will use a simulated dataset. hr_data To help explain the use of the 5 functions of dplyr

hr_data Help simulate an HR scenario where data on employees needs to be analyzed to find solutions to employee attrition.

by hr_data Consists of 8 variables:

No.ColumnData
1IDEmployee ID
2Nameชื่อพนักงาน
3DepartmentDepartment
4AgeAge
5EngagementEngagement Score (1 to 100)
6YearsAtCompanyDuration of Employment
7AttritionRiskRisk of resignation (Low, Medium, High)
8Salarysalary

Code for creating and browsing hr_data:

# Create the dataset
hr_data <- data.frame(
  ID = 1:15,
  Name = c("Alice", "Bob", "Carol", "David", "Eve", "Frank", "Grace", 
           "Henry", "Ivy", "Jack", "Karen", "Liam", "Mona", "Nate", "Olivia"),
  Department = c("HR", "IT", "Finance", "HR", "Sales", "IT", "Finance", 
                 "Sales", "IT", "HR", "Finance", "Sales", "IT", "HR", "Sales"),
  Age = c(34, 29, 45, 50, 27, 30, 42, 35, 31, 40, 38, 28, 33, 55, 26),
  Engagement = c(85, 70, 65, 55, 90, 75, 60, 88, 80, 50, 68, 72, 78, 40, 95),
  YearsAtCompany = c(5, 2, 15, 25, 1, 3, 10, 7, 4, 20, 12, 1, 6, 30, 0),
  AttritionRisk = c("Low", "Medium", "High", "High", "Low", "Medium", "High", 
                    "Low", "Medium", "High", "High", "Low", "Medium", "High", "Low"),
  Salary = c(55000, 60000, 70000, 75000, 50000, 62000, 68000, 58000, 
             61000, 77000, 72000, 51000, 64000, 80000, 49000)
)

# View the dataset
hr_data

Results:


✍️ Function Writing Pattern

Although all 5 functions have different roles, they are invoked in the same way:

func(dataset,
condition)
  • func = Function names, such as select, filter, arrange
  • dataset = Input dataset
  • condition = Conditions for the operation of the function

1️⃣ Function #1: select()

select() UseSelect column Required Fields

Examples:

The executive needs data that only includes employee names, departments, and engagement scores.

We can use select() Select only the desired columns:

# Select only desired columns
select(hr_data,
       Name,
       Department,
       Engagement)

Results:

.

Note:

Also select the column. select() We can specify the order of the columns to be displayed, for example, we want to display Department Prev Name Then write it down. Department, Name

.

dplyr There are helper functions that make selecting columns easier, such as:

FunctionMeaning
starts_with()Select the column that starts with x.
ends_with()Select the column ending with x.
contains()Select the column that contains the word x.
matches()Select the column that matches the regular expression.
last_col()Select the last column in the dataset.
~Select all columns except the specified column

.

We can rename a column using = such as FullName = Name So that the column header displays the word Fullname for Name


2️⃣ Function #2: filter()

filter() UseSelect row that match the specified criteria are displayed

Examples:

Management needs information on employees who are at high risk of resigning.

We can use filter() To set conditions for filtering data:

# Filter for high attrition risk
filter(hr_data,
       AttritionRisk == "High")

Results:

.

Note:

We can use Boolean operators and comparison operators together:

OperatorMeaning
==Equals sign
!=is not equal to
>More than
<Less than
&and
|or
!not

E.g.:

Management needs information on employees at high risk of resigning in the Finance department.

# Filter for high attrition risk in Finance
filter(hr_data,
       AttritionRisk == "High" & Department == "Finance")

Results:


3️⃣ Function #3: arrange()

arrange() UseSort dataOn Condition

Examples:

The management wants employee information sorted by engagement scores.

We can use arrange() Sort by the desired column:

# Sort employees by engagement
arrange(hr_data,
        Engagement)

Results:

.

Note:

Default of arrange() Sort from lowest to highest (A-Z)

If you want to sort from highest to lowest (Z-A), use desc() E.g.:

# Sort employees by engagement, from high to low
arrange(hr_data,
        desc(Engagement))

Results:


4️⃣ Function #4: summarize()

summarise() UseData parsingLess is more. It makes the information easier to understand.

Examples:

The administrator wants to know the average engagement score.

We can use summarise() To calculate the average:

# Calculate mean engagement
summarise(hr_data,
          mean(Engagement))

Results:

.

Note:

Functions commonly used with summarise() These are:

FunctionMeaning
mean()Calculate the average
min()Find the minimum value
max()Find the maximum value
sd()Calculate the standard deviation
n()Count the number of data points

.

summarise() Often used with group_by() To calculate statistical values by data group, such as the average performance score by risk level of resignation:

# Calculate mean engagement by attrition risk
summarise(group_by(hr_data, AttritionRisk),
          mean(Engagement))

Results:

.

In addition, we can name the column of statistical values using = Yes, for example:

# Naming the output
summarise(group_by(hr_data, AttritionRisk),
          AvgEng = mean(Engagement))

Results:


5️⃣ Function #5: mutate()

mutate() USED FOR:Create new dataFrom existing data

Examples:

The management wants to know how much time each employee has left before retirement.

We can use mutate() To create a new column that shows the number of years until retirement:

# Add a new column
mutate(hr_data,
       YearsUntilRetirement = 60 - Age)

Results:

From the results, it can be seen that the new column is added at the end (far right).

.

Note:

If you only want to see new information, we can change it. mutate() is transmute() Yes

After receiving new information, transmute() The original data will be discarded, and only the new data will be kept.


🫂 Putting Everything Together: Pipe Operator

We will see the true capabilities of dplyr When all 5 functions are used together, using pipe operator: %>% OR |>

The pipe operator is what helps send the output from one function to the input of the next function.

For example, from the code, calculate the average work score based on the risk level of previous resignations:

# Calculate mean engagement by attrition risk
summarise(group_by(hr_data, AttritionRisk),
          AvgEng = mean(Engagement))

If you use the pipe operator, you can write it like this:

# Calculate mean engagement by attrition risk
hr_data |>
  
  # Group by AttritionRisk
  group_by(AttritionRisk) |>
  
  # Calculate mean
  summarise(AvgEng = mean(Engagement))

Both sets of code give the same result:

However, it can be seen that the code using the pipe operator is clearer and easier to read because it doesn't require writing nested code.

.

Now, if we use the pipe operator to combine all 5 functions together, it will allow us to use the data to answer more complex questions.

Examples:

The management wants a list of employees at high risk of resignation, sorted by length of service and salary, from highest to lowest.

We can use the pipe operator together. group_by() + summarise() + arrange() To answer the question:

# Find employees with high attrition risk
# and sort by tenure and salary
hr_data |>
  
  # Filter for high attrition risk
  filter(AttritionRisk == "High") |>
  
  # Sort descending by tenure and salary
  arrange(desc(YearsAtCompany),
          desc(Salary))

Results:

.

OR

The management wants to know the number of employees and the average engagement scores for each department, with the departments ranked from highest to lowest average.

hr_data |> 
  
  # Group by department
  group_by(Department) |>
  
  # Calculate mean and count the number of employees
  summarise(AvgEng = mean(Engagement),
            EmpCount = n()) |>
  
  # Sort descending by average engagement
  arrange(desc(AvgEng))

Results:

.

OR

The management wants to know the proportion of employees in the high-risk group in each department, ranked from highest to lowest, and requests that the data be arranged as follows: Department, Proportion of high-risk employees, Total number of employees, Number of employees in the high-risk group.

hr_data |>
  
  # Group by department
  group_by(Department) |>
  
  # Count high attrition risk and find attrition risk ratio
  summarise(HighRiskCount = sum(AttritionRisk == "High"),
            TotalEmp = n(),
            HighRiskRatio = (HighRiskCount / TotalEmp) * 100) |>
  
  # Select desired columns
  select(Department, HighRiskRatio, TotalEmp, HighRiskCount) |>
  
  # Sort descending by high rish ratio
  arrange(desc(HighRiskRatio))

Results:


🔥 Summary of 5 Functions from dplyr

5 functions Basics of dplyr These are functions that can be used together to work with various types of data, such as employee data, efficiently.

No.FunctionExplain
1select()Select the desired column
2filter()Select the desired row
3arrange()Sort data
4sumamrise()Summary of Information
5mutate()Convert data

Note: Use %>% OR |> To connect functions together


Try it yourself!

For those who want to try using R to work with HR data, you can download the sample code from the article on GitHub.


📚 Read more about dplyr


✅ R Book for Psychologists: An R Book for Psychologists

📕 Please allow me to present the first book of my life. 😆

🙋 Anyone who is studying psychology or working in the field of psychology and is tired of using expensive software like SPSS and Excel to process data.

💪 I recommend R Book for Psychologists, a book that teaches how to use the R language for psychological data analysis. It is written for psychologists who have never had any experience writing code before.

In this book, we will lay the groundwork for the R language and show you how to perform common statistical analyses, such as:

  • Correlation
  • t-tests
  • ANOVA
  • Reliability
  • Factor analysis

🚀 After reading and following the examples in the R Book for Psychologists, everyone will no longer need to rely on SPSS and Excel for their work and will be able to analyze data independently with confidence.

Then everyone will be surprised why the R language is so easy. 🙂‍↕️

👉 For more details about the book, visit meb:

Comments

Leave a Reply