【问题标题】:Getting frequencies from time intervals in R [closed]从R中的时间间隔获取频率[关闭]
【发布时间】:2019-01-25 23:05:15
【问题描述】:

希望你能帮我解决我的问题。

例如,有关于人们上(时间 1)和下(时间 2)火车的数据。 我想知道的是在某个时间点有多少人在火车上,例如2018/01/01 16:00。查看数据集,可以看到当时火车上有两个人。 最后,我想得到一个表格,在一列中显示日期和小时,在另一列中显示人数。这在 R 中可能吗?

非常感谢!

我知道我不会给你很多信息。真的不知道如何在这里发布格式不错的东西...... 我不指望一个详细的解决方案,只是指出我正确的方向会很好。

【问题讨论】:

  • 是的,这是可能的,但如果没有可重复的示例,我们无法为您提供太多帮助。如果您的某个时间点在开始日期和结束日期之间,您似乎需要检查每一行,然后计算这是正确的次数。这个小例子可能会对你有所帮助:library(dplyr); library(lubridate); x = ymd_hms("2018-01-01 16:00:00"); between(x, ymd_hms("2018-01-01 15:00:00"), ymd_hms("2018-01-01 16:20:00")); between(x, ymd_hms("2018-01-01 10:00:00"), ymd_hms("2018-01-01 12:50:00"))

标签: r time


【解决方案1】:

这是一个小例子,火车上有 2 个人和 2 个兴趣点:

library(tidyverse)
library(lubridate)

# example dataframe (2 people on the train)
df = data.frame(start = c("2018-01-01 10:00:00", "2018-01-01 13:00:00"),
                end = c("2018-01-01 15:00:00", "2018-01-01 17:00:00"), stringsAsFactors = F)

# get a set of time points of interest
times = c("2018-01-01 16:00:00", "2018-01-01 09:00:00")


data.frame(times, stringsAsFactors = F) %>%  # for each time point of interest
  mutate(d = list(df)) %>%                   # join with inital dataset
  unnest() %>%                               # unnest data
  rowwise() %>%                              # for each row
  mutate(flag = between(ymd_hms(times), ymd_hms(start), ymd_hms(end))) %>% # add a flag value if the time point is between the start and end time
  group_by(times) %>%                        # for each time point
  summarise(NumPeople = sum(flag))           # add the flags to get number of users within the time frames

# # A tibble: 2 x 2
#   times               NumPeople
#   <chr>                   <int>
# 1 2018-01-01 09:00:00         0
# 2 2018-01-01 16:00:00         1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    相关资源
    最近更新 更多