0

I am using RStudio to write a script that simply populates a new column in a data.frame based upon a simple formula involving another column in the same data.frame. I eventually want to add an internal loop, which is why I think a for loop is the way to go. I am new to r so I am not sure. At some point in the development of the user defined function, BD, PS and LT (see below) will be arguments in a user defined function. I created a very simple data.frame for illustration. The question is: How do I get this loop or some formula that will populate the values of media_stock with the simple exponential decay formula in the loop?

TV = data.frame(cbind(cable = c(215, 144, 66, 400, 0, 0, 0, 0, 0, 0, 0, 500, 0, 0, 0, 0, 0, 77, 99, 108, 86, 118, 204, 119, 144, 0, 0, 0, 450, 361, 438, 170, 244, 0, 0, 0, 0, 0, 107, 122, 207, 274, 0, 0, 0, 0, 0, 0, 0, 752, 700,665),media_stock = NA))

PS = 0.30 
BD = 0 
LT = 6 

for(i in (LT+1):length(TV)){ 
  TV$media_stock[i-BD] <- TV$cable[i-BD] + PS*TV$media_stock[i-BD-1]
}

Thanks for any advice

1 Answer 1

1

There's two small mistakes in your current code that might fix your problem. The first is that you are using length(TV) to get at the number of rows in your data frame. What you want to use for this is nrow(TV) instead. The second is that all your value in the media_stock column are NA. When you apply your formula, no matter what you do to it arithmetically, the result will still be NA, so you need to initialize the first value of media_stock that you plan to use in your iteration. For example:

TV$media_stock[LT-BD] <- 1
for(i in (LT+1):nrow(TV)){ 
  TV$media_stock[i-BD] <- TV$cable[i-BD] + PS*TV$media_stock[i-BD-1]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sebkopf. I will try this and see what happens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.