【问题标题】:Delete specific values in R with zoo/xts使用 zoo/xts 删除 R 中的特定值
【发布时间】:2013-04-07 12:48:08
【问题描述】:

关于“在 R 中使用线性插值添加缺失的 xts/zoo 数据”的其他问题,您可以在此处找到 Add missing xts/zoo data with linear interpolation in R

但总的来说,我的数据还有一个问题 - 我确实有没有意义的“错误”值:

"2012-04-09 05:03:00",2
"2012-04-09 05:04:00",4
"2012-04-09 05:05:39",-10
"2012-04-09 05:09:00",0
"2012-04-09 05:10:00",1

所以替换缺失的日期有效:

y <- merge(y, zoo(,seq(start(y),end(y),by="min")), all=TRUE)
y <- na.approx(y)

但正如您所见,-10 没有意义,并且值不在 min:sec 处,值为 00。我需要像 na.rm 这样的解决方案。 谢谢!

【问题讨论】:

    标签: r time-series xts zoo missing-data


    【解决方案1】:

    不清楚你想做什么。但我猜你想从 xts 对象中删除一些异常值。如果您想要像“na.rm”这样的解决方案,一个想法是用NA 替换不需要的值,然后使用na.omit 删除它们。

    x <- read.zoo(text='
    "2012-04-09 05:03:00",2
    "2012-04-09 05:04:00",4
    "2012-04-09 05:05:39",-10
    "2012-04-09 05:09:00",0
    "2012-04-09 05:10:00",1',sep=',',tz='')
    
    x[x == -10] <- NA
    na.omit(x)
    
                        x
    2012-04-09 05:03:00 2
    2012-04-09 05:04:00 4
    2012-04-09 05:09:00 0
    2012-04-09 05:10:00 1
    

    编辑

    要获取每个日期的条件,例如,您可以查看 index(x) 并对其进行格式化。

    format(index(dat),'%S')
    [1] "00" "00" "39" "00" "00"
    

    但在这里我使用内置的.indexsec(另见.indexmin、.indexhour、..)

    dat[.indexsec(dat) != 0]
    2012-04-09 05:05:39 
                    -10
    

    【讨论】:

    • 正是我的意思 - 谢谢!这个解决方案是通过寻找一个特定的值 - 是否也有可能按日期?没有 h:m:00 - 几秒钟?
    【解决方案2】:

    以下是如何将低于阈值(在本例中为 0)的值替换为 NA。之后你可以运行na.approx

    # read in
    Lines <- '"2012-04-09 05:03:00",2
    "2012-04-09 05:04:00",4
    "2012-04-09 05:05:39",-10
    "2012-04-09 05:09:00",0
    "2012-04-09 05:10:00",1
    '
    data2 <- as.xts(read.zoo(text = Lines, sep = ",", tz = ""))
    
    # perform calculation
    data2[data2<0] <- NA
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-07
      • 2013-04-07
      • 2013-04-10
      • 2012-08-10
      • 2021-11-12
      • 1970-01-01
      • 2020-10-01
      • 2018-01-21
      相关资源
      最近更新 更多