【问题标题】:R: dplyr filter timestampR: dplyr 过滤器时间戳
【发布时间】:2017-04-22 11:12:21
【问题描述】:

我有以下由tbl_df 包装的数据框。请注意,第二列timestamp 在被tbl_df 包裹之前被格式化为timestamp=format(df[,2], format="%H:%M:%OS")

> out$ts_tbl
# A tibble: 1,903 × 3
         date    timestamp value
       <dttm>       <fctr> <int>
1  2016-07-04 09:15:00.099 8
2  2016-07-04 09:15:00.099 2
3  2016-07-04 09:15:00.099 9
4  2016-07-04 09:15:00.152 1
5  2016-07-04 09:15:00.152 2
6  2016-07-04 09:15:00.152 3
7  2016-07-04 09:15:00.152 5
8  2016-07-04 09:15:00.152 10
9  2016-07-04 09:15:00.152 10
10 2016-07-04 09:15:00.152 1
# ... with 1,903 more rows

不知何故,在用tbl_df 包装数据框后,时间戳列成为因素。

我的目标是能够过滤“09:16:00.000”之前的时间戳(或过滤一定范围内的时间戳)。我试过了:

> output$ts_tbl %>% filter(timestamp < "09:16:00.000")

然后我有以下输出抱怨时间戳是tbl_df 下的因素(如下所示)。有人可以帮我吗?

# A tibble: 0 × 3
# ... with 3 variables: date <dttm>, timestamp <fctr>, value <int>
Warning message:
In Ops.factor(c(14L, 14L, 14L, 35L, 35L, 35L, 35L, 35L, 35L, 35L,  :
  ‘<’ not meaningful for factors

【问题讨论】:

  • 但是第二列只包含没有日期的时间。我怎样才能转换它?
  • 我在下面发布了一个解决方案

标签: r timestamp dplyr


【解决方案1】:

我们可以使用chron 将其转换为times 类并执行filter

library(chron)
library(dplyr)
df %>% 
    filter(times(timestamp)< times("09:16:00"))
# A tibble: 7 × 3
#        date    timestamp value
#       <chr>       <fctr> <int>
#1 2016-07-04 09:15:00.099     8
#2 2016-07-04 09:15:00.099     2
#3 2016-07-04 09:15:00.099     9
#4 2016-07-04 09:15:00.152     1
#5 2016-07-04 09:15:00.152     2
#6 2016-07-04 09:15:00.152     3
#7 2016-07-04 09:15:00.152     5

数据

df <- structure(list(date = c("2016-07-04", "2016-07-04", "2016-07-04", 
"2016-07-04", "2016-07-04", "2016-07-04", "2016-07-04", "2016-07-04", 
"2016-07-04", "2016-07-04"), timestamp = structure(c(1L, 1L, 
1L, 2L, 2L, 2L, 2L, 3L, 3L, 4L), .Label = c("09:15:00.099", "09:15:00.152", 
"09:16:00.152", "09:17:00.152"), class = "factor"), value = c(8L, 
2L, 9L, 1L, 2L, 3L, 5L, 10L, 10L, 1L)), .Names = c("date", "timestamp", 
"value"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", 
 "9", "10"), class = c("tbl_df", "tbl", "data.frame"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2016-06-28
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多