数组中值的平均值(Average of values in an array)
我有一个数组,并且想要构建一个循环,它将从数组的第一个值开始平均每个第二个值,在第一个循环之后,循环应该以数组的第二个值开始。
例如:
3,6,18,10,2结果应该是:
7.666,8,10 for 7.6666= (3+18+2)/3 for 8= (6+10)/2 for 10=(18+2)/2提前致谢
I have an array and want to build a loop which averages every second value starting at the first value of the array and after the first round the loop should start with the second value of the array.
For example:
3,6,18,10,2The result should be:
7.666,8,10 for 7.6666= (3+18+2)/3 for 8= (6+10)/2 for 10=(18+2)/2Thanks in advance
最满意答案
你在找这样的东西吗?
x <- c(3,6,18,10,2) n <- length(x) sapply(seq_len(n-2), function(X) { mean(x[seq(X, n, by=2)]) }) # [1] 7.666667 8.000000 10.000000然后更有趣的事情, 赚取 @ mnel的upvote;)
n <- length(x) m <- matrix(0, n, n-2) ii <- row(m) - col(m) m[ii >= 0 & !ii %% 2] <- 1 colSums(x * m)/colSums(m) # [1] 7.666667 8.000000 10.000000Are you looking for something like this?
x <- c(3,6,18,10,2) n <- length(x) sapply(seq_len(n-2), function(X) { mean(x[seq(X, n, by=2)]) }) # [1] 7.666667 8.000000 10.000000And then something more interesting, to earn @mnel's upvote ;)
n <- length(x) m <- matrix(0, n, n-2) ii <- row(m) - col(m) m[ii >= 0 & !ii %% 2] <- 1 colSums(x * m)/colSums(m) # [1] 7.666667 8.000000 10.000000更多推荐
发布评论