r - 如何根据这个特定逻辑在我的 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 问题中提供的答案,但我不知道如何为我的问题实现其中一个:
解决方案
下面使用mutate
dplyr 中的函数来创建新列并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"
))
推荐阅读
- java - robots.mouseMove 没有通过视频证据移动到正确的位置
- azure - Deploy multiple linked ARM templates in Private Storage Container using single SAS token
- android - Does updating an app on Google Play cause the current version's internal storage data to be deleted?
- spring - Spring boot security login verify failed
- c# - Comparing to booleans gives false when they have the same value
- ios - 用不同的内容偏移值连接两个 ScrollView
- assembly - Continuation of Comment Line
- swift - Swift 'mutating' 关键字是什么意思?
- java - Libgdx 和 Android Studio:标签不显示任何文本
- macos - 如何在 Matlab 界面上继续运行 shell 脚本?