【发布时间】:2014-06-03 21:05:19
【问题描述】:
我正在尝试从我的数据集中的“日期”变量中仅从以下特定工作日“周四”、“周五”和“周六”中提取数据。
> head(tidyFile)
Date Time Global_active_power Global_reactive_power Voltage Global_intensity
66637 2007-02-01 00:00:00 0.326 0.128 243.15 1.4
66638 2007-02-01 00:01:00 0.326 0.130 243.32 1.4
66639 2007-02-01 00:02:00 0.324 0.132 243.51 1.4
66640 2007-02-01 00:03:00 0.324 0.134 243.90 1.4
66641 2007-02-01 00:04:00 0.322 0.130 243.16 1.4
66642 2007-02-01 00:05:00 0.320 0.126 242.29 1.4
Sub_metering_1 Sub_metering_2 Sub_metering_3
66637 0 0 0
66638 0 0 0
66639 0 0 0
66640 0 0 0
66641 0 0 0
66642 0 0 0
我使用以下代码在我需要的日期范围之间划分子集:
tidyFile <- newFile[newFile$Date >= "2007-02-01" & newFile$Date <= "2007-02-02", ]
但是我子集的方式可能有问题,因为当我在这个子集中调用“Thurs”、“Fri”和“Sat”时,我得到了 NA 值,这是不对的。我是否应该与时俱进,以确保我包含上述日期?
最后,我需要按“星期四”、“星期五”和“星期六”进一步对数据进行子集化,但我似乎无法做到这一点。我尝试了以下方法:
library(lubridate)
with(tidyFile[wday(tidyFile, label=T) == "Thurs" & "Fri" & "Sat"])
返回错误信息:
Error in wday(tidyFile, label = T) : unused argument (label = T)
更新
这些是我创建脚本所采取的步骤:
## STEP 1: Set working directory
setwd("/Users/usaid/datasciencecoursera/data/")
## STEP 2: Create a new object 'newFile' and read .txt file into R
newFile <- read.table("course_4_proj_1.txt", header=TRUE, sep=";", na.strings = "?", nrows= 1000000, stringsAsFactors=FALSE, as.is=TRUE)
## STEP 3: Create a new object 'newFile$Date' and format dates (into date class)
newFile$Date <- as.Date(newFile$Date, format = "%d/%m/%Y")
newFile$Date <- strptime(newFile$Date, format = "%d/%m/%Y", tz = "")
## STEP 4: Create a new object 'tidyFile' and subset data based on date range provided in Project 1 instructions
tidyFile <- newFile[newFile$Date >= "2007-02-01" & newFile$Date <= "2007-02-02", ]
## STEP 5: Subset data by "Thurs", "Fri", "Sat"
library(lubridate)
with(tidyFile, wday(Date, label = TRUE))
days <- with(tidyFile, wday(Date, label = TRUE) %in% c("Thurs","Fri","Sat"))
tidyFile[days, ]
当我运行第 5 步时,我收到下面提到的错误消息。
【问题讨论】:
-
您的布尔条件不正确。你可能想使用
%in%。 -
%in% 会包含在上面的代码中的什么地方?
-
如果您想要周四、周五或周六的任何一个工作日,请
... %in% c("Thurs","Fri","Sat")。 -
我明白了。但我想要所有三个工作日的数据。
-
您已经循环了各种不同的错误代码,其中一些我什至还没有触及。您的
with语法不正确。您最后一次尝试修复您对%in%的使用从根本上改变了括号的位置。我认为你真的需要回去学习一些基本的 R 教程和手册。