【问题标题】:Select data range from timestamp based on row.names根据 row.names 从时间戳中选择数据范围
【发布时间】:2019-05-22 10:29:44
【问题描述】:

如果我有一个数据框,我希望根据时间范围选择一个训练集

df <- data.frame(timestamp = seq(as.POSIXct('2013-08-02 12:00:00'),
                                as.POSIXct('2013-08-06 05:00:00'), len =(45), 
                   x = sample(1:100, 45), y = sample(200:500, 45)))

我现在将时间戳转换为 row.names

row.names(df) = df$timestamp

既然我已经索引了 row.names,我应该能够为训练集选择一个范围:

 # Select the range 
 s = '2013-08-02 12:00:00'
 e = '2013-08-03 10:15:00'

 # Select the training dataset 

 training = df[s:e,]

但是当我运行上面的代码时,我得到了以下错误:

 #Error in s:e : NA/NaN argument
 #In addition: Warning messages:
 #1: In `[.data.frame`(df, s:e, ) : NAs introduced by coercion
 #2: In `[.data.frame`(df, s:e, ) : NAs introduced by coercion

谁能解释一下我在这里做错了什么!

我知道 ts 或其他一些软件包可以解决这个问题,但没有任何我可以使用的基本 R 函数。

我在发布问题之前查看的答案。

Select rows within a particular time range

【问题讨论】:

    标签: r timestamp


    【解决方案1】:

    : 不会为您提供要选择的行范围。您需要找出各自的索引,然后在它们之间创建一个序列,然后再创建一个子集

    df[which(row.names(df) == s) : which(row.names(df) == e), , drop = FALSE]
    
    #                              timestamp
    #2013-08-02 12:00:00 2013-08-02 12:00:00
    #2013-08-02 14:01:21 2013-08-02 14:01:21
    #2013-08-02 16:02:43 2013-08-02 16:02:43
    #2013-08-02 18:04:05 2013-08-02 18:04:05
    #2013-08-02 20:05:27 2013-08-02 20:05:27
    #2013-08-02 22:06:49 2013-08-02 22:06:49
    #2013-08-03 00:08:10 2013-08-03 00:08:10
    #2013-08-03 02:09:32 2013-08-03 02:09:32
    #2013-08-03 04:10:54 2013-08-03 04:10:54
    #2013-08-03 06:12:16 2013-08-03 06:12:16
    #2013-08-03 08:13:38 2013-08-03 08:13:38
    #2013-08-03 10:15:00 2013-08-03 10:15:00
    

    如果se 可能有多个值,最好在这种情况下使用which.max,因为which.max 返回第一个最大值的索引。

    此外,您根本不需要转换为rownames。您可以使用 timestamp 列本身实现相同的目的。

    df[which.max(df$timestamp == s) : which.max(df$timestamp == e), , drop = FALSE]
    

    【讨论】:

      【解决方案2】:

      这是一个简单的索引指令。

      inx <- as.POSIXct(s) <= row.names(df) & row.names(df) <= as.POSIXct(e)
      df[inx, ]
      

      为了清楚起见,我将其保留为这样,您可以将其设为单线。

      【讨论】:

        猜你喜欢
        • 2013-01-10
        • 1970-01-01
        • 1970-01-01
        • 2011-11-16
        • 1970-01-01
        • 2017-12-30
        • 2014-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多