数据框上的过滤日期

时间:2020-04-07 16:22:50

标签: r date datetime

我需要过滤R中的大型数据集(100K +观测值),使其仅包含2014年至今的数据。原始数据包含2001年至今的观测值。这是可用于工作的示例数据:

   df <- data.frame(student = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), GPA = c(4,3.7,2.0,1.3,2.9,2.4,4.0,3.0,2.0,3.3),
                 Failed_Course = c(1,0,1,1,1,1,1,1,1,0), 
                 Exam_date = c ("01/06/2010 06:55:00 AM", "03/30/2020 11:55:00 PM","12/30/2014 12:55:00 AM","04/20/2016 11:55:00 PM","09/28/2014 11:12:00 PM","07/30/2017 11:55:00 PM", "4/3/2005 09:55:00 PM", 
                                "8/20/2004 11:55:00 PM","8/20/2015 11:22:00 AM","6/22/2001 08:55:00 PM"))

2 个答案:

答案 0 :(得分:3)

使用dplyrlubridate

library(lubridate)
library(dplyr)

# Converts variable Exam_date into date format (month,date,year_hours,mins,secs)


df$Exam_date <- mdy_hms(df$Exam_date)


# Creates a new variable called date_year that only contains the year,
#filters for years greater than or equal to 2014, 
#and drops the date_year variable

df <- df %>% 
      mutate(date_year = year(Exam_date)) %>%
      filter(date_year >= 2014) %>%
      select(-date_year)

答案 1 :(得分:1)

这是基本的R方法。

df$Exam_date <- as.POSIXct(df$Exam_date,format = "%m/%d/%Y %I:%M:%S %p", tz="UTC")
df[df$Exam_date > as.POSIXct("2014-01-01 00:00:00"),]
#  student GPA Failed_Course           Exam_date
#2       2 3.7             0 2020-03-30 23:55:00
#3       3 2.0             1 2014-12-30 00:55:00
#4       4 1.3             1 2016-04-20 23:55:00
#5       5 2.9             1 2014-09-28 23:12:00
#6       6 2.4             1 2017-07-30 23:55:00
#9       9 2.0             1 2015-08-20 11:22:00