【问题标题】:R Counting related dates in an XTS (or data.frame) objectR在XTS(或data.frame)对象中计算相关日期
【发布时间】:2017-08-19 09:37:27
【问题描述】:

在我的研究中,我正在分析气象站的历史风速(如果趋势是增加或减少等)。 现在我每天都有一个值。 我想计算彼此相关的天数(例如 1958-03-18、19、20...)。对于每一年,我都想知道连续 3 天以上发生了多少(风暴)天。

示例:

1982-01-30  41.04
1982-02-02  45.72
1982-02-03  46.8
1982-02-04  41.04
1982-02-12  39.24
1982-02-17  53.28
1982-02-18  49.68
1982-02-19  40.32
1982-03-01  46.08

1982年2月2次是情况(2,3,4)和(17,18,19)。

有谁知道如何计算并将其放入新表中以供进一步分析/绘图?

1982 23
1983 7
1984 11
.
.
.

至少计算一年中的所有天数也会对我有所帮助。

亲切的问候 萨沙

【问题讨论】:

  • 您在一天中使用的阈值是多少才能成为风暴日?
  • 假设您添加一个数据为 1,1,1,2,2,2,3,3,3.. 的列来对相邻日期进行分组。然后熔化你的表以折叠每个组中最小值的行,最后计算熔化表中该最小值超过阈值的行。您需要重复这些步骤,列为 1,1,2,2,2,3,3,3,4,4.. 和 1,2,2,2,3,3,3,4,4, 4..
  • 我们的数据库是每天每小时的值。使用每天 24 个值的最大值。之后,我们选择该值大于 39 公里/小时的所有日子。

标签: r date count xts


【解决方案1】:

以下是识别暴风雨日(根据您的评论风 > 39)和连续三个暴风雨日的日期的简单方法。

#create example data
fakedates <- as.Date("1982-01-01")+(1:730)
fakewind <- sample(1:80, length(fakedates), replace = TRUE)
dateyear <- format(fakedates, "%Y")

df <- data.frame("dates"=fakedates, "maxwind"=fakewind, "year"=dateyear)

#identify 'storm' days where max wind is >39
df$storm <- df$maxwind > 39  #identify storm days

# ensure original data is in chronological order, otherwise you would need to sort first
# e.g.  if(is.unsorted(original$dates), sort(original$dates, .... etc)

#identify 3-day storms - undetermined for last two days in the record
df$storm3 <-
  c(df$storm[1:(length(df$storm) - 2)] &
      df$storm[2:(length(df$storm) - 1)] &
      df$storm[3:(length(df$storm))], "unknown", "unknown")

#select all storm day records
dfs <- df[df$storm == TRUE, c(1:3)]

#select only dates of 3-day storms
dfs3 <- df[df$storm3== TRUE,(1:3)]

您的输出将如下所示:

> head(dfs3)
        dates maxwind year
12 1982-01-13      57 1982
13 1982-01-14      47 1982
33 1982-02-03      65 1982
49 1982-02-19      79 1982
61 1982-03-03      49 1982
68 1982-03-10      55 1982

您可以按年份进行汇总,并根据所有暴风雨天数 (dfs) 或仅三天暴风雨天数 (dfs3) 进行任何其他分析。

当您更熟悉 R 时,您可以通过其他各种方式来处理任务,例如使用包 dplyr

【讨论】:

  • 嗨 Jules,我对 R 不是很熟悉,但我尝试使用您的建议。非常感谢,看起来我可以使用它 :) 使用 dplyr 我想检查例如在所有车站中发生的日期。
猜你喜欢
  • 2021-06-09
  • 2011-03-31
  • 1970-01-01
  • 2016-01-16
  • 2018-09-03
  • 2021-11-12
  • 2020-09-14
  • 2014-05-17
  • 1970-01-01
相关资源
最近更新 更多