【问题标题】:How can I create a new column for seasons based on date ranges?如何根据日期范围为季节创建新列?
【发布时间】:2018-03-06 21:21:02
【问题描述】:
#make a horrible data frame:

ottawadates <- as.Date(c("2016-08-04", "2016-09-03", "2016-02-15", "2016-03-29, "2016-09-27"))
othervariable <- c(1, 2, 4, 5, 6)
df = data.frame(othervariable, ottawadates)

好的,我想做的就是创建一个名为“seasons”的新字段。我想使用日期范围来指示哪些日期属于相应的季节。为了清楚起见,我的实际数据集具有正确日期格式的日期,所以我猜索引日期范围相当简单。

即12 月 21 日 - 3 月 19 日是冬季。 3 月 20 日 - 6 月 20 日是春天 6 月 21 日 - 9 月 21 日是夏季 9 月 23 日 - 12 月 20 日是秋季

我觉得这是一个 for 循环的工作,但我太新手不知道如何去做。

谢谢。我很感激!

【问题讨论】:

  • 如果您的示例包含与您的数据格式相同的数据,您将获得更好的答案。因此,如果您的数据集使用日期,请在示例中使用日期。
  • 感谢您的建议。我更新了示例数据,使其采用日期格式。至于链接,谢谢。我只是很困惑如何使用这些块,以便它们遍历我自己的数据集并将正确的季节添加到新的“季节”列中的相应行。

标签: r for-loop dataframe character


【解决方案1】:

您可以使用lubridateifelse 根据日期范围查找季节。假设季节为WinterOther season,一种方法可能是:

#data
ottawadates <- as.Date(c("2016-08-04", "2016-09-03", "2016-02-15"))
othervariable <- c(1, 2, 4)
df = data.frame(othervariable, ottawadates)

library(lubridate)
df$ottawadates <- ymd(df$ottawadates)

#Evaluate season
df$season <- ifelse((month(df$ottawadates) %in% c(1, 2)) |
                  (month(df$ottawadates) == 12L & day(df$ottawadates) >= 21L) |
                  (month(df$ottawadates) == 3L & day(df$ottawadates) <= 19L),
                  "Winter", 
                  ifelse( (month(df$ottawadates) %in% c(4, 5)) |
                  (month(df$ottawadates) == 3L & day(df$ottawadates) >= 20L) |
                  (month(df$ottawadates) == 6L & day(df$ottawadates) <= 20L),
                   "Spring",
                   ifelse( (month(df$ottawadates) %in% c(7, 8)) |
                           (month(df$ottawadates) == 6L & day(df$ottawadates) >= 21L) |
                           (month(df$ottawadates) == 9L & day(df$ottawadates) <= 21L),
                           "Summer", "Fall")))


df
#  othervariable ottawadates  season
#1             1  2016-08-04  Summer
#2             2  2016-09-03  Summer
#3             4  2016-02-15  Winter

【讨论】:

  • 谢谢。我将如何使用 Spring 等?只是更多 ifelse 语句?你会怎么写?
  • @hmnoidk 请为 spring 添加范围,我可以修改我的答案。基本上相同的方式你必须添加嵌套的ifelse
  • 再次感谢。我添加了日期范围。
  • @hmnoidk 看看。
猜你喜欢
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多