R日期不在字符列表中

时间:2015-02-02 15:28:43

标签: r date conditional-statements

我有一个包含多个变量的数据框,其中包括Date格式的日期(df $ date)。

我还有字符格式的日期列表(例如" 2013-07-14")。我需要从数据框中删除列表日期。

我尝试了以下但没有一个正在运作。

datestoremove <- as.character(datestoremove) #from list to character format
require(lubridate)
test1 <- ymd(datestoremove)  #yields NA


grepl(df$date[3600],datestoremove) # Try to identify character pattern. Doesn't work as it yields FALSE even when it is true (I know df$date[3600] is in the list.

datestoremove <- strptime(datestoremove, format = "%Y-%m-%d") # Passing datestoremove to date format. Unsucessfully. 
test1 <- strptime(datestoremove,"%Y-%m-%d")

test2 <- df[which(!(df$date[3600] %in% datestoremove)),] #Seems to work but it does not transfer the valid rows to test2. So test2 is empty. 
test3 <- subset(df, !(df$date %in% datestoremove)) 

数据:

    df <- structure(list(date = structure(c(15930, 15931, 15931, 15931, 
    15931, 15931), class = "Date"), st1count = c(259L, 4L, 36L, 54L, 
    67L, 56L)), .Names = c("date", "st1count"), class = "data.frame", row.names = 3420:3425)

datestoremove <- list(structure(c(15931, 15979, 16252, 16322), class = "Date"))

1 个答案:

答案 0 :(得分:2)

您可以尝试运行此操作,而无需将列表转换为字符:

df[!(df$date %in% datestoremove[[1]]),]