我正在尝试计算人们使用Leada提供的数据集所拍摄的自行车频率。
以下是代码:
library(dplyr)
setAs("character", "POSIXlt", function(from) strptime(from, format = "%m/%d/%y %H:%M"))
d <- read.csv("http://mandrillapp.com/track/click/30315607/s3-us-west-1.amazonaws.com?p=eyJzIjoiemxlVjNUREczQ2l5UFVPeEFCalNUdmlDYTgwIiwidiI6MSwicCI6IntcInVcIjozMDMxNTYwNyxcInZcIjoxLFwidXJsXCI6XCJodHRwczpcXFwvXFxcL3MzLXVzLXdlc3QtMS5hbWF6b25hd3MuY29tXFxcL2RhdGF5ZWFyXFxcL2Jpa2VfdHJpcF9kYXRhLmNzdlwiLFwiaWRcIjpcImEyODNiNjMzOWJkOTQxMGM5ZjlkYzE0MmQ0NDQ5YmU4XCIsXCJ1cmxfaWRzXCI6W1wiMTVlYzMzNWM1NDRlMTM1ZDI0YjAwODE4ZjI5YTdkMmFkZjU2NWQ2MVwiXX0ifQ",
colClasses = c("numeric", "numeric", "POSIXlt", "factor", "numeric", "POSIXlt", "factor", "numeric", "numeric", "factor", "character"),
stringsAsFactors = T)
names(d)[9] <- "BikeNo"
d <- tbl_df(d)
d <- d %>% mutate(Weekday = factor(weekdays(Start.Date)))
d %>% group_by(Weekday)
%>% summarise(Total = n())
%>% select(Weekday, Total)
很奇怪,但是dplyr不希望按工作日分组数据:
错误:列&#39; Start.Date&#39;有不支持的类型
为什么它关心Start.Date列,我按哪个因素分组? 您可以在本地运行代码以重现错误:它将自动下载数据。
P.S。我使用的是dplyr版本:dplyr_0.3.0.2
答案 0 :(得分:7)
在处理日期时,lubridate包非常有用。 以下是解析Start.Date和End.Date的代码,提取工作日,然后按工作日分组:
library(dplyr)
library(lubridate)
# For some reason your instruction to load the csv directly from a url
# didn't work. I save the csv to a temporary directory.
d <- read.csv("/tmp/bike_trip_data.csv", colClasses = c("numeric", "numeric", "character", "factor", "numeric", "character", "factor", "numeric", "numeric", "factor", "character"), stringsAsFactors = T)
names(d)[9] <- "BikeNo"
d <- tbl_df(d)
d <- d %>%
mutate(
Start.Date = parse_date_time(Start.Date,"%m/%d/%y %H:%M"),
End.Date = parse_date_time(End.Date,"%m/%d/%y %H:%M"),
Weekday = wday(Start.Date, label=TRUE, abbr=FALSE))
d %>%
group_by(Weekday) %>%
summarise(Total = n())
# Weekday Total
# 1 Sunday 10587
# 2 Monday 23138
# 3 Tuesday 24678
# 4 Wednesday 23651
# 5 Thursday 25265
# 6 Friday 24283
# 7 Saturday 12413
答案 1 :(得分:2)
如果这个问题早已被遗忘,我很抱歉,但是当我使用更简单的解决方案从plyr包中调用arrange函数时,我很惊讶地看到每个人都建议转换为POSIX.ct或字符。 {1}},因为它似乎没有POSIXlt格式的问题。由于我通常不是找到R中问题的最简单解决方案的人,我开始认为它有问题。它与dplyr版本不一样吗?