You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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(...) becomes integer(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')) is TRUE for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:30:53