Stewart Wiseman
Stewart Wiseman

Reputation: 705

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

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
 ))

Upvotes: 1

Views: 2503

Answers (6)

Yonghao
Yonghao

Reputation: 176

Will this work?

tmp %>% 
  mutate(y = 1*(y=="Yes"))

# 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

Upvotes: 0

Jaap
Jaap

Reputation: 83215

Another solution:

# base R style
tmp$y <- match(tmp$y, c("No","Yes")) - 1L

# tidyverse style
tmp <- tmp %>% 
  mutate(y = match(y, c("No","Yes")) - 1L)

which both give:

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

Upvotes: 2

Ric S
Ric S

Reputation: 9247

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

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 388907

You can directly do :

tmp$y <- +(tmp$y == 'Yes')
#similar to
#tmp$y <- as.integer(tmp$y == 'Yes')
tmp

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

Upvotes: 1

zeebrah
zeebrah

Reputation: 126

I came up with a quick and dirty fix using ifelse() function.

tmp <- tibble(x = 1:7, y = c("No", "Yes", NA, "Yes", "Yes", "Yes", "No"))
tmp_new <- as_tibble(ifelse(is.na(tmp) == T,NA, ifelse(tmp == "No",0,1)))

Upvotes: -1

Limey
Limey

Reputation: 12461

Yopu almost had it.

tmp <- tmp %>% mutate(y=ifelse(is.na(y), y, y == "Yes"))

Upvotes: -1

Related Questions