3.1 C
London
Friday, December 20, 2024
HomeTidyverse in Rdplyr in RHow to Recode Values Using dplyr

How to Recode Values Using dplyr

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Occasionally you may be interested in recoding certain values in a dataframe in R. Fortunately this can easily be done using the recode() function from the dplyr package.

This tutorial shows several examples of how to use this function in practice.

Example 1: Recode a Single Column in a Dataframe

The following code shows how to recode a single column in a dataframe:

library(dplyr)

#create dataframe 
df #view dataframe 
df

#change 'Win' and 'Loss' to '1' and '0'
df %>% mutate(result=recode(result, 'Win'='1', 'Loss'='0'))

       player points result
1      A     24      1
2      B     29      0
3      C     13      1
4      D     15      0

Example 2: Recode a Single Column in a Dataframe and Provide NA Values

The following code shows how to recode a single column in a dataframe and give a value of NA to any value that is not explicitly given a new value:

library(dplyr)

#create dataframe 
df #view dataframe 
df

#change 'Win' to '1' and give all other values a value of NA
df %>% mutate(result=recode(result, 'Win'='1', .default=NA_character_))

       player points result
1      A     24      1
2      B     29      
3      C     13      1
4      D     15      

Example 3: Recode Multiple Columns in a Dataframe

The following code shows how to recode multiple columns at once in a dataframe:

library(dplyr)

#create dataframe 
df #recode 'player' and 'result' columns
df %>% mutate(player=recode(player, 'A'='Z'),
              result=recode(result, 'Win'='1', 'Loss'='0'))

       player points result
1      Z     24      1
2      B     29      0
3      C     13      1
4      D     15      0

You can find the complete documentation for the recode() function here.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories