对于x的每个位置,我想计算多少个数> 5.这是我的代码,使用for循环:
x<-c(2,8,4,9,10,6,7,3,1,5)
y <- vector()
for (i in seq_along(x)) {
x1 <- x[1:i]
y <- c(y, length(x1[x1>5]))
}
> y
[1] 0 1 1 2 3 4 5 5 5 5
Run Code Online (Sandbox Code Playgroud)
你能帮我用purrr做吗?可以在这里使用purrr :: reduce吗?
cumsum
功能可以做到这一点
cumsum(x>5)
#[1] 0 1 1 2 3 4 5 5 5 5
Run Code Online (Sandbox Code Playgroud)
你可以使用accumulate()
来自purrr
:
accumulate(x > 5, `+`)
#[1] 0 1 1 2 3 4 5 5 5 5
Run Code Online (Sandbox Code Playgroud)
这基本上是一个包装周围Reduce()
有accumulate = TRUE
accumulate <- function(.x, .f, ..., .init) {
.f <- as_function(.f, ...)
f <- function(x, y) {
.f(x, y, ...)
}
Reduce(f, .x, init = .init, accumulate = TRUE)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
523 次 |
最近记录: |