Home > database >  Create column with a specific elements conditioned to the other column
Create column with a specific elements conditioned to the other column

Time:04-26

I have the following script:

library(lubridate)
library(tidyverse)

date_vec <- seq(dmy("01-11-2020"), dmy("15-07-2022"), by = "day")

df <- tibble(date = date_vec, description = NA)

limpmerg <- dmy("04-11-2020", "16-11-2020", "25-11-2020", "03-12-2020", 
                "20-12-2020", "28-12-2020", "08-01-2021", "21-01-2021", 
                "28-01-2021", "24-02-2021", "06-03-2021", "11-03-2021", 
                "22-03-2021", "30-03-2021", "04-04-2021", "19-04-2021", 
                "28-04-2021", "25-05-2021", "08-06-2021", "15-06-2021", 
                "21-06-2021", "24-06-2021", "30-06-2021", "09-07-2021", 
                "15-07-2021")

falhequip <- dmy("20-11-2020", "21-11-2020", "23-11-2020", "24-11-2020",
                 "25-11-2020", "04-01-2021", "05-01-2021", "06-01-2021", 
                 "07-01-2021", "24-01-2021", "25-01-2021", "26-01-2021")

I would add in column description, of df a text "clean" to dates in vector limpmerg, a text "failing" to dates in vector falhequip. To the other dates, I would add text "collect".

How can I do this?

Thank's

CodePudding user response:

We may use case_when

library(dplyr)
df1 <- df %>%
  mutate(description = case_when(date %in% limpmerg ~ "clean", 
                                date %in% falhequip ~ "failing",
                                 TRUE ~ "collect"))

CodePudding user response:

In base R you can do this using a simple nested ifelse statement, though the case_when approach by @akrun is likely preferred in your situation:

df$description <- ifelse(df$date %in% limpmerg, "clean",
                         ifelse(df$date %in% falhequip, "failing", "collect"))

Output:

# date       description
# <date>     <chr>      
#   1 2020-11-01 collect    
# 2 2020-11-02 collect    
# 3 2020-11-03 collect    
# 4 2020-11-04 clean      
# 5 2020-11-05 collect    
# 6 2020-11-06 collect    
# 7 2020-11-07 collect 
  • Related