dplyr mutate converting "No" to 0 and "Yes" to 1

Stewart Wiseman

I have a column of type chr that I need as boolean (but leaving the NAs as NAs). The desired conversion is: No = 0, Yes = 1, NA = NA

tmp <- tibble(x = 1:7, y = c("No", "Yes", NA, "Yes", "Yes", "Yes", "No"))

I used the following to mutate; however I don't want a new variable but just change the original y variable:

tmp = tmp %>% mutate(
 z = case_when(
     y=="No" ~ 0,
     y=="Yes" ~ 1
 ))
Ric S

Just another solution which can be useful in case you will need to recode more values in the future

library(dplyr)
tmp$y <- recode(tmp$y, "No" = 0, "Yes" = 1)

or using mutate in a pipeline

tmp %>% 
  mutate(y = recode(y, "No" = 0, "Yes" = 1))

Output

# A tibble: 7 x 2
#       x     y
#   <int> <dbl>
# 1     1     0
# 2     2     1
# 3     3    NA
# 4     4     1
# 5     5     1
# 6     6     1
# 7     7     0

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

converting the difference in vectors to between 0 and 1

mutate many columns in dplyr for log(1+x)

Converting (0,1,0, 0, 1, 1, 1) to (0, 0, 0, 1, 0, 1, 2) in R

dplyr: mutate() and mutate_if()

Python - how to convert 1/0 to yes/no (in pandas.DataFrame)?

converting logical true/false to numeric 1/0?

Converting 'no' and 'yes' into 0 and 1 in pandas dataframe

How to change yes/no in a column to 1 and 0

How to mutate a column using dplyr with a value when any of the columns contain a 1 otherwise 0

r - use dplyr to mutate column 2 if column 1 equals

Laravel - Display No for 0 and Yes for 1 on index view blade

exp function in dplyr mutate returning 1's

converting '0'...'n' into '0' '1' up to 'n'

Why do "yes/no" values in Microsoft Access map to -1 and 0?

Efficient way for converting Yes/No to 1/0 in Excel or SPSS

Return the value of 0 and 1 from database to No / Yes in a select box

Error near CASE when converting bit (1/0 or true/false) to Yes/No

Have two radio buttons (yes or no), with values of 0 or 1 to input to database. How to echo user choice with 'yes' or 'no'?

Combining dplyr::do() with dplyr::mutate?

r program changing yes/no variable to 1/0 - " variable 'medal' is not a factor"

Diff Tool which Outputs 1/0 // Yes/No

Converting Yes to 1 and No to 0 in python

How to display Yes and No instead of binary 1 & 0 in fpdf?

How to display Yes/No instead of 1/0 in Angular

Converting 0x1 to 1 in java

Check if string is in Variant and then replace Yes/No results with 1/0 respectively

Convert yes/no column to 1/0 in Power BI

in R mutate TRUE FALSE to 1 0

How to mutate numeric to factor and keep levels "0" and "1" and not "1" and "2"