简体   繁体   中英

Selecting Date Range from Column in R

I have a dataset in R which I read in using read.table (Table Name a). I want to select dates from '2007-02-01' to '2007-02-02'. The Current Date Column is of class "Character".

     Date     
1 16/12/2006               
2 16/12/2006            
3 16/12/2006             
4 16/12/2006            
5 16/12/2006              
6 16/12/2006             

I tried the following:
1. as.Date(a$Date) returns date in the format "0016-12-20"
2. a[a$Date >= '2007-02-01' & a$Date <= '2007-02-01'] returns all rows with 0 variables
3. strptime(a$Date,'%d%b%Y') returns NA values

Convert date to date class and subset:

df$Date <- as.Date(df$Date, '%d/%m/%Y')
subset(df, Date >= as.Date('2007-02-01') & Date <= as.Date('2007-02-02'))

You can also use:

library(dplyr)

df %>%
  mutate(Date = lubridate::dmy(Date)) %>%
  filter(Date >= as.Date('2007-02-01') & Date <= as.Date('2007-02-02'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM