使用cut函数时breaks参数出错

时间:2019-03-29 10:14:08

标签: r cut

我正在学习R,我需要根据以下数据创建双向表:

> head(datanet)
   Date & Time [Local]  distance travelled
1:    18/06/2018 03:08  15.959366
2:    18/06/2018 03:12  22.535566
3:    18/06/2018 03:16  12.036834
4:    18/06/2018 03:20  18.738134
5:    18/06/2018 03:24  26.781879
6:    18/06/2018 03:28  8.341659

我期望的输出应如下表所示,其中有一个hour列代表一天中的时间(一天中的24小时为24个条目),还有几个dist_tra on yyyy-mm-dd项,平均每天每小时每小时的每小时行驶距离。像这样:

head(dist.byHour[1:3])
  hour dist_tra on 06/07/2018  dist_tra on 06/08/2018
1:   00              25.834355              29.388140
2:   01                     NA               8.329956
3:   02                     NA              31.506390
4:   03              33.464954              20.995957
5:   04               6.406513              17.035749
6:   05              28.254438              38.803171

通过在线查找并与一些同事交谈,我获得了以下脚本。但是,使用cut()时出现错误消息:

library(tidyverse)

datanet$datehour <- cut(datanet[[1]], breaks = "hours")

dist.byHour <- aggregate(meters ~ datehour, datanet, mean, na.rm = TRUE)
dist.byHour$datehour <- as.POSIXct(dist.byHour$datehour)
dist.byHour$hour <- format(dist.byHour$datehour, "%H")
dist.byHour$datehour <- as.Date(dist.byHour$datehour)
dist.byHour <- dist.byHour[c(3, 1, 2)]

dist.byHour <- dist.byHour %>%
  spread(datehour, -hour)

names(dist.byHour)[-1] <- paste("dist_tra on", names(dist.byHour)[-1])

错误为:

> datanet$datehour <- cut(datanet[[1]], breaks = "hours")
Error in cut.default(datanet[[1]], breaks = "hours") : 
  'x' must be numeric

关于如何解决此问题的任何想法?这是我正在处理的一项重要任务,因此我们将不胜感激!

1 个答案:

答案 0 :(得分:1)

实际上不需要使用剪切,您可以使用组:

library(lubridate)
library(tidyverse)

# sample data
date <- c("18/06/2018 03:08", "18/06/2018 03:12", "18/06/2018 04:20", "19/06/2018 03:16", "19/06/2018 03:20", "19/06/2018 04:20")
distance <- c(15.959366,  22.535566, 12.036834,  18.738134, 12.036834, 22.535566)

df <- data.frame(date, distance)

df %>% 
  mutate(date = dmy_hm(date)) %>% #coerce to date object
  group_by(day = date(date), hour = hour(date)) %>% # group by day and hour
  summarise(dist = mean(distance)) %>% # average distance traveled in that hour
  spread(day, dist) # re-arrange dataframe