如何在R语言中筛选xts对象以排除指定日期?
Got it, let's adjust your code to exclude that specific date instead of selecting it.
First, here's your original code that picks out March 30th's data:
library(xts) xts1 <- xts(x=1:10, order.by=as.Date('2018-03-31')-1:10) xts1['2018-03-30']
To exclude that date, you have two solid options:
Option 1: Using which() with negation
xts1[-which(index(xts1) == '2018-03-30')]
This finds the position of the target date in the index and excludes that row by negating the position. It works fine if you know the date definitely exists in your xts object.
Option 2: Using %in% with logical negation (Better choice)
xts1[!(index(xts1) %in% as.Date('2018-03-30'))]
This is the recommended approach because it handles edge cases smoothly. For example, if you try to exclude a date that's not present in your xts object (like 2018-03-20):
- With Option 1:
which(index(xts1) == '2018-03-20')returns an empty vector, so-which(...)becomesinteger(0)—this would result in an empty xts object, which isn't what you want (you'd expect to keep all data when the date isn't there). - With Option 2:
!(index(xts1) %in% as.Date('2018-03-20'))isTRUEfor every row, so you get the full original dataset, which is the correct behavior.
Content of this question originates from Stack Exchange, asked by jmuhlenkamp
相关产品推荐
相关产品推荐

