gpt4 book ai didi

R xts - 使用 last() 时下标越界

转载 作者:行者123 更新时间:2023-12-01 23:08:06 25 4
gpt4 key购买 nike

我在 R 中的 xts 包中使用 last() 函数时发现了一个奇怪的错误。

我有一个 dim 740*1 的 xts 对象,但 last(data, 1) 返回错误:

> tail(data)
[,1]
2017-02-28 2.092
2017-03-01 2.093
2017-03-02 NA
2017-03-03 NA
2017-03-06 NA
2017-03-07 NA
> dim(data)
[1] 740 1
> last(data,1)
Error in x[[order(order_by)[n]]] : subscript out of bounds

你能帮我理解为什么会这样吗?

最佳答案

当函数被另一个同样加载到 R session 中的包中的相同函数名屏蔽时,就会发生这种情况。

dplyr::last(data, 1)

Error in x[[order(order_by)[n]]] : subscript out of bounds

last(data, 1)
# [,1]
#2017-04-11 5

在上面,它是 dplyr lastxts::last 屏蔽了,所以在这种情况下它工作得很好。根据加载包的顺序(这里我们在 dplyr 之后加载了 xts),这可能会发生。假设,我们在 xts 之后加载 dplyr 到一个新的 R session 中,反之亦然

library(xts)
#Loading required package: zoo

#Attaching package: ‘zoo’

#The following objects are masked from ‘package:base’:

#as.Date, as.Date.numeric

library(dplyr)

#Attaching package: ‘dplyr’

#The following objects are masked from ‘package:xts’:

#first, last ####note this line


data <- xts(1:5, order.by = Sys.Date()+1:5)
last(data, 1)

Error in x[[order(order_by)[n]]] : subscript out of bounds

这里,选项是使用::

xts::last(data, 1)
# [,1]
#2017-04-11 5

数据

data <- xts(1:5, order.by = Sys.Date()+1:5)

关于R xts - 使用 last() 时下标越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43244763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com