On 11-03-14 21:09, David Winsemius wrote:
On Mar 14, 2011, at 3:52 PM, Sascha Vieweg wrote:
Hello, I need some form of a "permutative" operation on a numeric vector x
x = (v1, v2, v3, ..., vN)
that produces
x.r = (v1, v1+2, v1+v2+v3, ... v1+v2+...+vN)
If the operation is sum() I can run
x <- 5:8
m <- matrix(rep(x, length(x)), ncol=length(x))
(x.r <- rowsum(m * upper.tri(m, diag=TRUE), rep(1, length(x))))
But there's two things I don't know and kindly request help or comments
upon:
(1) What is the fastest code to perfom the forestanding operation?
(2) Is there a more general function for tasks like this, not only with the
sum procedure applied to the vector? Specifically, the zeros in the matrix
may cause problems with other operations than sum.
Perhaps this:
fplus <- function(x, y) paste(x,y, sep="+")
Reduce(fplus, vv, accumulate=TRUE)
[1] "v1" "v1+v2"
[3] "v1+v2+v3" "v1+v2+v3+v4"
[5] "v1+v2+v3+v4+v5" "v1+v2+v3+v4+v5+v6"
[7] "v1+v2+v3+v4+v5+v6+v7" "v1+v2+v3+v4+v5+v6+v7+v8"
[9] "v1+v2+v3+v4+v5+v6+v7+v8+v9" "v1+v2+v3+v4+v5+v6+v7+v8+v9+v10"
Thanks, David, after trying around I found that one:
x <- 5:8
sapply(1:length(x), function(y) sum(x[1:y]))
I keep your code in my records for operations that cannot be
applied with function names.
--
Sascha Vieweg, saschav...@gmail.com
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.