ifelse and using binary(TRUE /FALSE) variable

hi I have a column in my data like this:

is_animal
TRUE
FALSE
TRUE
TRUE
TRUE
FALSE
TRUE

code:

data %>%
mutate(flag = ifelse(is_animal == TRUE, "Animal", "NO"))

is the above the preferred way to go about creating this variable ? I tried using below:

data %>%
mutate(x = ifelse(isTRUE(is_animal == TRUE), "Animal", "NO))

and I got all of the columns "NO"... so not one were "Animal". which is so strange. any advices appreciated thank u !!

Your code works for me, as does a modified version that takes advantage of the fact that the is_animal column is already a boolean.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
data <- data.frame(is_animal=c(TRUE,FALSE,TRUE,TRUE,TRUE,FALSE,TRUE))
data
#>   is_animal
#> 1      TRUE
#> 2     FALSE
#> 3      TRUE
#> 4      TRUE
#> 5      TRUE
#> 6     FALSE
#> 7      TRUE

data %>%
  mutate(flag = ifelse(is_animal == TRUE, "Animal", "NO"))        
#>   is_animal   flag
#> 1      TRUE Animal
#> 2     FALSE     NO
#> 3      TRUE Animal
#> 4      TRUE Animal
#> 5      TRUE Animal
#> 6     FALSE     NO
#> 7      TRUE Animal

data %>%
  mutate(flag = ifelse(is_animal, "Animal", "NO"))       
#>   is_animal   flag
#> 1      TRUE Animal
#> 2     FALSE     NO
#> 3      TRUE Animal
#> 4      TRUE Animal
#> 5      TRUE Animal
#> 6     FALSE     NO
#> 7      TRUE Animal

Created on 2022-09-30 with reprex v2.0.2

Is it possible that your is_animal column is text instead of a logical value? What is the result of

class(data$is_animal)
1 Like

it is a logical value! your second option works great for me :slight_smile: it seems cleaner than mine.thank u!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.