condition ifelse in mutate function

Hello,

I tried to use the function mutate(completed=ifelse()) w/o succes.
You will find below the reprex

rm(list = ls())
library(dplyr)
#> 
#> Attachement du package : 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(rlang)

data<- data.frame(stringsAsFactors = FALSE,
                                     A= c("A","B","C"),
                                     B=c("17/05/19","","")
)

tab<-data %>%
     mutate(completed=ifelse(!is.null(.data$B),"Yes","On progress"))

I should obtained "Yes" for the row A and "On progress" for the row B,C.
But that's not the fact. I obtain "Yes" in each rows.

Have you an idea?
Thanks in advance

Hi there,

Your column B entries in rows "B" and "C" are not NULL, they are empty strings. So you want to do this instead:

tab <- data %>%
     mutate(completed=ifelse(B != "","Yes","On progress"))

Hope that helps.

1 Like

@headsortails beat me to it, almost.

The B == "" logical test returns TRUE if there is "", so the following part of the statement should be "On Progress" and the second part (FALSE) "Yes". Because of the danger that an entry might be " ", however, I would do the following

suppressPackageStartupMessages(library(dplyr)) 
suppressPackageStartupMessages(library(lubridate)) 
dat <- data.frame(stringsAsFactors = FALSE,
         A= c("A","B","C"),
         B=c("17/05/19","","")
        )

tab <-dat %>% mutate(completed = ifelse(is.Date(ymd(B)) & !is.na(ymd(B)), "Yes","On progress"))

tab
#>   A        B   completed
#> 1 A 17/05/19         Yes
#> 2 B          On progress
#> 3 C          On progress

Created on 2020-03-01 by the reprex package (v0.3.0)

Thank you for your efficient response!

1 Like

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