Ani*_*yal 10 r sequence modulo
假设我有一个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
Run Code Online (Sandbox Code Playgroud)
这里cumprod
只是一个示例函数。我可能还必须以交替顺序使用其他功能。
我们可以rowCumprods
在创建后以简洁的方式做到这一点matrix
(假设vector
它的长度是偶数)
library(matrixStats)
c(rowCumprods(matrix(x, nrow = 2)))
Run Code Online (Sandbox Code Playgroud)
-输出
[1] 5 6 35 48 315 480 3465 5760 45045 80640
Run Code Online (Sandbox Code Playgroud)
如果它可以是奇数长度,那么只需NA
在末尾附加一个
c(rowCumprods(matrix(c(x, list(NULL, NA)[[1 +
(length(x) %%2 != 0)]]), nrow = 2)))
Run Code Online (Sandbox Code Playgroud)
-输出
[1] 5 6 35 48 315 480 3465 5760 45045 80640
Run Code Online (Sandbox Code Playgroud)
或者我们可以用通用的方式来做到这一点ave
(适用于偶数/奇数长度)
ave(x, seq_along(x) %% 2, FUN = cumprod)
[1] 5 6 35 48 315 480 3465 5760 45045 80640
Run Code Online (Sandbox Code Playgroud)
选择奇数 ( 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
Run Code Online (Sandbox Code Playgroud)
要处理奇数向量长度,您需要将结果截断为向量的长度。
x = 1:5
c(rbind(cumprod(x[c(TRUE, FALSE)]), cumprod(x[c(FALSE, TRUE)])))[1:length(x)]
# [1] 1 2 3 8 15
Run Code Online (Sandbox Code Playgroud)
当较短的结果向量(对应于偶数索引(少一个元素))在rbind
步骤中被回收时,将出现警告。
偶数和奇数元素的一种选择可能是:
c(t(apply(matrix(x, 2, sum(seq_along(x) %% 2)), 1, cumprod)))[1:length(x)]
Run Code Online (Sandbox Code Playgroud)
与x <- 1:5
:
[1] 1 2 3 8 15
Run Code Online (Sandbox Code Playgroud)
与x <- 1:6
:
[1] 1 2 3 8 15 48
Run Code Online (Sandbox Code Playgroud)
或者一个不太有效的选择,但是,没有任何警告:
y <- Reduce(`c`, sapply(split(setNames(x, seq_along(x)), !seq_along(x) %% 2), cumprod))
y[order(as.numeric(names(y)))]
Run Code Online (Sandbox Code Playgroud)
另一种选择 - 取一个序列,然后将结果填回:
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
Run Code Online (Sandbox Code Playgroud)
或者,如果您想打高尔夫球:
s <- seq(1, length(x), 2)
replace(replace(x, s, cumprod(x[s])), -s, cumprod(x[-s]))
# [1] 5 6 35 48 315 480 3465 5760 45045 80640
Run Code Online (Sandbox Code Playgroud)