如何在文本文件的数据操作期间过滤日期?

How to filter on date during data manipulation of text file?

我正在完成 coursera 的作业,需要创建包含 2 月 7 日的前两天的数据子集。

这是我的代码:

library(sqldf)

# set directory 
setwd("C:/Users/thoma/Desktop/Files/Programming/R/EDA/EDAWk1")

# unzip source data
temp <- tempfile()
download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip", temp)
data <- read.table(unz(temp, "household_power_consumption.txt"), header = TRUE, sep = ';')


# we only want a specified range of dates 
data_2 <- sqldf("
                select
                * 
                from data
                where Date in ('2007-02-01','2007-02-02')
                ")

中间数据集 'data' 工作正常,但我得到 data_2 的空值。有谁知道为什么会这样?

您可以在 base R 中执行此操作:

data_2 <- subset(data, Date %in% as.Date(c('2007-02-01','2007-02-02')))

或使用dplyrlubridate

library(dplyr)
library(lubridate)

data_2 <- data %>% filter(month(Date) == 2 & day(Date) <= 2)

选项data.table

library(data.table)
setDT(data)[Date %in% as.IDate(c('2007-02-01','2007-02-02'))]