2

For such Data Frame, I was trying to select some rows within a specific date range:

nasdaq=read.csv("nasdaq.csv")
head(nasdaq)

        Date Close.Price
1 2013-08-05     3692.95
2 2013-08-06     3665.77
3 2013-08-07     3654.01
4 2013-08-08     3669.12
5 2013-08-09     3660.11
6 2013-08-12     3669.95

what I have tried so far is:

chunk=subset(nasdaq,nasdaq$Date>=as.Date("2013-08-05") & nasdaq$Date<=as.Date("2018-08-03"))

Warning messages:

1: In eval(e, x, parent.frame()) :
  Incompatible methods ("Ops.factor", "Ops.Date") for ">="
2: In eval(e, x, parent.frame()) :
  Incompatible methods ("Ops.factor", "Ops.Date") for "<="

I have also tried...

 chunk=nasdaq[nasdaq$Date>=as.Date("2013-08-05") & nasdaq$Date<=as.Date("2018-08-03"),]

Warning messages:

1: In `[.data.frame`(nasdaq, nasdaq$Date >= as.Date("2013-08-05") &  :
  Incompatible methods ("Ops.factor", "Ops.Date") for ">="
2: In `[.data.frame`(nasdaq, nasdaq$Date >= as.Date("2013-08-05") &  :
  Incompatible methods ("Ops.factor", "Ops.Date") for "<="

I have tried both of above without as.Date function but doesn't work, Please advise where I may be going wrong?

1
  • 2
    you have read in the dates as a factor by not doing read.csv("nasdaq.csv", stringsAsFactors = F). That is step 1. Commented Aug 15, 2018 at 22:45

3 Answers 3

3

The warning message tells you the issue. Column Date in your data frame is a factor, not a date. This is because you did not specify stringsAsFactors = FALSE in read.csv (then Date would be a character).

There are several ways to fix this. You can convert to dates after reading the data:

nasdaq$Date <- as.Date(nasdaq$Date, "%Y-%m-%d")

Or you can use the colClasses argument when reading the file:

nasdaq <- read.csv("nasdaq.csv", header = TRUE, colClasses = c("Date", "numeric"))

Or you could use readr::read_csv, which will recognise that the column contains dates.

Sign up to request clarification or add additional context in comments.

Comments

0

This should work for you,

library(dplyr)
library(lubridate)

# dummmy data
test_data <- data.frame(
  Date = ymd(c("2013-08-05","2013-08-06 ","2013-08-07")),
  Close.Price = c(3692.95,3665.77,3654.01)
)

test_data %>%
  filter(Date >= ymd("2013-08-05") & Date <= ymd("2013-08-07"))

        Date Close.Price
1 2013-08-05     3692.95
2 2013-08-06     3665.77
3 2013-08-07     3654.01

Comments

0

You need to specify the format of the date string in the as.Date() function before you can use it in the subset function

nasdaq$Date <- as.Date(nasdaq$Date, format = "%Y-%m-%d")
chunk <- subset(nasdaq,nasdaq$Date >= "2013-08-05" & nasdaq$Date <= "2018-08-03")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.