首页 > 解决方案 > 如何根据这个特定逻辑在我的 R 数据框中创建一个新变量(列)?

问题描述

我有一个R数据框,其中一列是YYYY-MM-DD格式中的日期列。

假设我的数据框被调用df1并且日期列被调用ref.date,我如何Category根据以下逻辑创建一个新列(被调用):

If **ref.date** between `2018-04-01` and `2019-04-01` then **Yr1**

If **ref.date** between `2019-04-01` and `2020-04-01` then **Yr2**

If **ref.date** between `2020-04-01` and `2021-04-01` then **Yr3**

Else **Not Stated**

任何帮助将非常感激。

注意:我查看了这个 StackOverflow 问题中提供的答案,但我不知道如何为我的问题实现其中一个:

R中等效的案例语句

标签: r

解决方案


下面使用mutatedplyr 中的函数来创建新列并lubridate帮助识别间隔:

library(dplyr)
library(lubridate)

df1 <- data.frame(
  ref.date = ymd(
    "2020-06-05",
    "2020-03-05",
    "2018-05-12",
    "2015-01-30"
    )
  )


mutate(df1, Category = case_when(
    ref.date %within% interval("2018-04-01", "2019-04-01") ~ "Yr1",
    ref.date %within% interval("2019-04-01", "2020-04-01") ~ "Yr2",
    ref.date %within% interval("2020-04-01", "2021-04-01") ~ "Yr3",
    TRUE ~ "Other"
    ))

推荐阅读