-1

Look, what I want to do: [In Excel is clear and easy, but in R I have a problem...:(]

Column A 1 2 3 4 5
Column B 0 9 2 1 7

That's my real "algorithm":

Column C 
(first value) = mean(Column A) = 3
(second value) = ((mean(Column A)*4) + 0)/5 =  2,4
(third value) = ((second value*4) + 9)/5 = 3,72
etc.

So we have:

#   A B  C
# 1 1 0  3
# 2 2 9 2,4
# 3 3 2 3,72
# 4 4 1 3,37
# 5 5 7 2,90

This is my actually code with your suggestion:

a <- c(1:5)
b <- c(0,9,0,1,7,0)

matrix <- data.frame(A=a,B=b)
matrix <- c(mean(matrix$A), (cumsum(matrix$B) + (mean(matrix$A)*4))/5)

This is solution: 2.4 4.2 4.2 4.4 5.8 (WRONG !!)

Of course R write me error that: "replacement has 6 rows, data has 5" but this isn't relevant...I only want to know, how should I do it??

Blazej
  • 19
  • 3
  • 1
    -1: see [What have you tried?](http://whathaveyoutried.com) and http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – sgibb Jul 18 '13 at 09:42
  • Welcome to SO. As Blazej pointed out, it is good practice to explain what you have tried and where you are stuck. This way we can help you learn, rather than just giving a magic incantation that solves your problem. – Richie Cotton Jul 18 '13 at 11:13
  • I can't resist suggesting that any statement containing both the words "Excel" and "clear" should be auto-downvoted by 10. But that aside, your algorithm for "column C" is unclear. In addition, since the values in `C` have no relationship to the `A` and `B` values in the same rows, I recommend against assembling the data in that sort of array. – Carl Witthoft Jul 18 '13 at 12:00

2 Answers2

1

You could use ?cumsum:

a <- 1:5
b <- c(0, 9, 2, 1, 7)

mean(a) + cumsum(b)
# [1]  3 12 14 15 22

UPDATE:

It seems you want to run a (weighted) moving average. Maybe you should have a look at the TTR package.

Please find an easy approach below:

wma <- function(b, startValue, a=4/5) {
  m <- double(length(b)+1)
  m[1] <- startValue
  for (i in seq(along=b)) {
    m[i+1] <- a * m[i] + (1-a) * b[i]
  }
  return(m)
}

wma(b, mean(a))
# [1] 3.00000 2.40000 3.72000 3.37600 2.90080 3.72064
sgibb
  • 25,396
  • 3
  • 68
  • 74
  • Sgibb you didn't understand my problem....look again what I want to do, please :) – Blazej Jul 18 '13 at 11:16
  • @Blazej: Your first problem was completely different. I couldn't understand your real problem first because you didn't describe your problem. – sgibb Jul 18 '13 at 11:50
0

This solves your issue:

mydf<-data.frame(A=1:5, B=c(0,9,2,1,7))
mydf$C<-cumsum(mydf$B)+mean(mydf$A)

mydf 
#   A B  C
# 1 1 0  3
# 2 2 9 12
# 3 3 2 14
# 4 4 1 15
# 5 5 7 22

Hope it helps.

Dr. Mike
  • 2,451
  • 4
  • 24
  • 36