我假设您的数据框是纯文本,因为您是从 csv 文件中读取它的。您可以使用dput 命令与我们分享。这是我之前准备的:
df = structure(list(
Date = c("2015-12-17 07:26:00", "2015-12-17 11:04:00", "2015-06-18 12:32:00"),
Crime = structure(c(3L, 2L, 1L), .Label = c("Murder", "Theft", "Vandalism"), class = "factor")),
class = "data.frame", row.names = c(NA, -3L), .Names = c("Date", "Crime"))
您可以使用lubridate 的ymd_hms 命令将Date 列转换为实际日期:
library(lubridate)
df$Date = ymd_hms(df$Date)
然后你可以将 Date-Time 构造转换为纯日:
df$Date = as.Date(df$Date)
现在您可以按常规方式通过Date 和Crime 进行聚合。这是dplyr的方式:
library(dplyr)
df %>% group_by(Date, Crime) %>% summarise(count = n())
输出:
# A tibble: 3 x 3
# Groups: Date [?]
Date Crime count
<date> <fctr> <int>
1 2015-06-18 Murder 1
2 2015-12-17 Theft 1
3 2015-12-17 Vandalism 1