R 通告 array/vector
R circular array/vector
是否存在实现 FIFO 意义上的循环数组或向量的 R 包?
假设我们有这个数组:
2 4 7 1
当在位置 1 插入一个新的观察值(比如 3)时,我希望第 n 个元素被第 n-1 个元素替换:
3 2 4 7
您可以尝试 c()
并截断结果的长度。
x <- c(2, 4, 7, 1)
c(3, x)[1:length(x)]
# [1] 3 2 4 7
此方法不会复制 x
tracemem(x)
# [1] "<0x3cb5998>"
c(3, x)[1:length(x)]
# [1] 3 2 4 7
untracemem(x)
append()
的源代码看起来可能还有一些有用的方法可以尝试。
append
# function (x, values, after = length(x))
# {
# lengx <- length(x)
# if (!after)
# c(values, x)
# else if (after >= lengx)
# c(x, values)
# else c(x[1L:after], values, x[(after + 1L):lengx])
# }
# <bytecode: 0x31ac490>
# <environment: namespace:base>
嗯,Richard Scriven's solution is most likely the way to go but if you're in an adventurous mood you can try Rexamine/DataStructures:
> devtools::install_github("Rexamine/DataStructures")
> library(DataStructures)
> q <- queue_create()
> queue_empty(q)
[1] TRUE
> for (i in c(1, 7, 4, 2)) { queue_push(q, i) }
> queue_empty(q)
[1] FALSE
> queue_pop(q)
[1] 1
> format(q)
[1] "7" "4" "2"
> queue_push(q, 3)
很难说它是否足够稳定,可以在实践中使用,而且它似乎只比简单的串联快一点点。
是否存在实现 FIFO 意义上的循环数组或向量的 R 包?
假设我们有这个数组:
2 4 7 1
当在位置 1 插入一个新的观察值(比如 3)时,我希望第 n 个元素被第 n-1 个元素替换:
3 2 4 7
您可以尝试 c()
并截断结果的长度。
x <- c(2, 4, 7, 1)
c(3, x)[1:length(x)]
# [1] 3 2 4 7
此方法不会复制 x
tracemem(x)
# [1] "<0x3cb5998>"
c(3, x)[1:length(x)]
# [1] 3 2 4 7
untracemem(x)
append()
的源代码看起来可能还有一些有用的方法可以尝试。
append
# function (x, values, after = length(x))
# {
# lengx <- length(x)
# if (!after)
# c(values, x)
# else if (after >= lengx)
# c(x, values)
# else c(x[1L:after], values, x[(after + 1L):lengx])
# }
# <bytecode: 0x31ac490>
# <environment: namespace:base>
嗯,Richard Scriven's solution is most likely the way to go but if you're in an adventurous mood you can try Rexamine/DataStructures:
> devtools::install_github("Rexamine/DataStructures")
> library(DataStructures)
> q <- queue_create()
> queue_empty(q)
[1] TRUE
> for (i in c(1, 7, 4, 2)) { queue_push(q, i) }
> queue_empty(q)
[1] FALSE
> queue_pop(q)
[1] 1
> format(q)
[1] "7" "4" "2"
> queue_push(q, 3)
很难说它是否足够稳定,可以在实践中使用,而且它似乎只比简单的串联快一点点。