问题描述
假设我有一个包含 x
元素的向量 n
。我想在 cumprod
的每个备用数字上使用任何矢量化函数,例如 x
,即每 1、3、5 等等,以及 2、4、6 等等。我正在添加一个 reprex 并尝试了代码。该代码有效,但似乎我不必要地走了很长的路,并且可以缩短代码。可以吗?
x <- 5:14
cumprod((x * (seq_along(x) %% 2)) + (seq_along(x)-1) %% 2) * seq_along(x) %% 2 +
cumprod((x * ((seq_along(x)-1) %% 2)) + seq_along(x) %% 2) * (seq_along(x)-1) %% 2
#> [1] 5 6 35 48 315 480 3465 5760 45045 80640
这里的 cumprod
只是一个示例函数。我可能还需要交替使用其他函数。
解决方法
选择奇数 (c(TRUE,FALSE)
) 或偶数 (c(FALSE,TRUE)
) 索引。编织两个结果向量 (c(rbind
)
c(rbind(cumprod(x[c(TRUE,FALSE)]),cumprod(x[c(FALSE,TRUE)])))
# [1] 5 6 35 48 315 480 3465 5760 45045 80640
要处理奇数向量长度,您需要将结果截断为向量长度。
x = 1:5
c(rbind(cumprod(x[c(TRUE,TRUE)])))[1:length(x)]
# [1] 1 2 3 8 15
当较短的结果向量(对应于偶数索引(少一个元素))在 rbind
步骤中被回收时,将出现警告。
偶数和奇数元素的一种选择可能是:
c(t(apply(matrix(x,2,sum(seq_along(x) %% 2)),1,cumprod)))[1:length(x)]
使用x <- 1:5
:
[1] 1 2 3 8 15
使用x <- 1:6
:
[1] 1 2 3 8 15 48
或者一个不太有效的选项,但是没有任何警告:
y <- Reduce(`c`,sapply(split(setNames(x,seq_along(x)),!seq_along(x) %% 2),cumprod))
y[order(as.numeric(names(y)))]
,
我们可以在创建 rowCumprods
后使用 matrix
以简洁的方式完成此操作(假设 vector
的长度为偶数)
library(matrixStats)
c(rowCumprods(matrix(x,nrow = 2)))
-输出
[1] 5 6 35 48 315 480 3465 5760 45045 80640
如果它可以是奇数长度,那么只需在末尾附加一个 NA
c(rowCumprods(matrix(c(x,list(NULL,NA)[[1 +
(length(x) %%2 != 0)]]),nrow = 2)))
-输出
[1] 5 6 35 48 315 480 3465 5760 45045 80640
或者我们可以使用 ave
以通用方式执行此操作(适用于偶数/奇数长度)
ave(x,seq_along(x) %% 2,FUN = cumprod)
[1] 5 6 35 48 315 480 3465 5760 45045 80640
,
另一种选择 - 取一个序列,然后将结果填回:
x <- 5:14
s <- seq(1,length(x),2)
o <- x
o[s] <- cumprod(x[s])
o[-s] <- cumprod(x[-s])
o
# [1] 5 6 35 48 315 480 3465 5760 45045 80640
或者如果你想打高尔夫球:
s <- seq(1,2)
replace(replace(x,s,cumprod(x[s])),-s,cumprod(x[-s]))
# [1] 5 6 35 48 315 480 3465 5760 45045 80640
,
更新的解决方案
这可能听起来有点冗长,但它适用于奇数和偶数长度以及@Henrik 的自定义向量:
x <- 5:14
lapply(split(x,!(seq_len(length(x)) %% 2)),cumprod) |>
setNames(c("a","b")) |>
list2env(globalenv())
c(a,b)[order(c(seq_along(a)*2 - 1,seq_along(b)*2))]
[1] 5 6 35 48 315 480 3465 5760 45045 80640
使用奇数向量:
x <- 5:13
[1] 5 6 35 48 315 480 3465 5760 45045
或者用x = c(1,3,4)
[1] 1 0 3 0
最后是x = c(2,4,4)
:
[1] 2 4 4 16