【问题标题】:Choosing rows containing only times between time x and time y选择仅包含时间 x 和时间 y 之间的时间的行
【发布时间】:2014-01-28 15:33:31
【问题描述】:

我有一个带有 df$Time 列的时间序列。我还有一列包含当天的日出时间 (df$Sunrise) 和另一列包含日落时间 (df$Sunset)。

我想将我的数据分成白天和黑夜两部分。 IE。我想选择白天的时间在日出和日落之间以及晚上的日落和日出之间的行。

我不确定最好的解决方法是什么。是否可以在 ifelse 语句中使用时间?还是有一些我不知道的功能可以帮助我?

df$Time 当前存储为一个因素。 df$Sunrise 和 df$Sunset 存储为 POSIXct。

我的数据示例:

Time       Sunrise               Sunset
00:01:00   2009-09-17 07:41:30   2009-09-17 20:05:30
00:02:00   2009-09-17 07:41:30   2009-09-17 20:05:30
00:02:00   2009-09-17 07:41:30   2009-09-17 20:05:30
00:04:00   2009-09-17 07:41:30   2009-09-17 20:05:30

在此示例中,我希望显示的所有时间都显示为夜晚。

【问题讨论】:

  • 你能展示一些示例数据吗?了解 df$Time 是否存储为日期、数字或字符值以及这些值的形式非常重要。

标签: r if-statement dataframe time-series


【解决方案1】:
df.day<-df[df$Time>df$Sunrise & df$Time<df$Sunset, ]
df.night<-df[df$Time<df$Sunrise & df$Time>df$Sunset, ]

在没有一些数据可以查看的情况下,我认为这应该会提供一些帮助。本质上,您正在创建两个数据框,一个在白天只有带有 df$Time 的行,一个在夜间

【讨论】:

  • 谢谢,它似乎适用于白天数据框,但返回 0 个夜间观测值,返回没有值介于日落和日出之间。我被难住了。
【解决方案2】:

这有望解决问题。

# read in (slightly edited) data
df<-data.frame(Time=c("07:40:00","07:42:00","15:02:00","20:06:00"),Sunrise=c("2009-09-17    07:41:30","2009-09-17 07:41:30","2009-09-17 07:41:30","2009-09-17 07:41:30"),Sunset=c("2009-09-17 20:05:30", "2009-09-17 20:05:30", "2009-09-17 20:05:30", "2009-09-17 20:05:30"))

# convert character to POSIXct
df$Sunrise<-as.POSIXct(df$Sunrise,format="%Y-%m-%d %H:%M:%S")
df$Sunset<-as.POSIXct(df$Sunset,format="%Y-%m-%d %H:%M:%S")

# add date to Time variable and convert to POSIXct
df$Time<-as.POSIXct(paste(strptime(df$Sunrise,"%Y-%m-%d"),df$Time),format="%Y-%m-%d %H:%M:%S")

# identify times during the day
df.day<-df[df$Time>df$Sunrise & df$Time<df$Sunset, ]
# identify times NOT during the day
df.night<-df[!(df$Time>df$Sunrise & df$Time<df$Sunset), ]

我应该在之前的回复中使用 not (!) 运算符来查找夜间时间。我原以为您只有一个数字变量来表示时间,而我之前没有使用过 POSIXct 数据。不过,这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多