创建具有以另一列为条件的特定元素的列

Create column with a specific elements conditioned to the other column

我有以下脚本:

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

我会在 df 的列描述中添加一个文本“干净”到向量 limpmerg 中的日期,一个文本“失败”到向量 falhequip 中的日期。对于其他日期,我会添加文本“收集”。

我该怎么做?

谢谢

我们可以使用case_when

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

在基础 R 中,您可以使用简单的嵌套 ifelse 语句来执行此操作,尽管在您的情况下可能更喜欢 @akrun 的 case_when 方法:

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

输出:

# 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