0

I'm trying to write a loop that will iterate through columns 64:111 in a data frame, and set [64,1] = 0, then [65,1:2] = 0, then [66,1:3] = 0 etc (Months_out starts at 0 and increments by 1). I can't tell why my loop is only running once, what am I doing wrong?

for (i in 64:111) {
   Prod1[cbind(1:Prod1$Months_Out+1,i)] <- 0
}
www
  • 38,575
  • 12
  • 48
  • 84
Jess
  • 15
  • 3
  • 2
    It would help if you provided a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output. It would probably be safe to scale down the problem to a more manageable size for the question. – MrFlick Aug 17 '17 at 18:15
  • 1
    If you are looping through columns 64 through 111, then what does `[64,1] = 0` mean? This typically means the element in row 64 and column 1. If that is incorrect, please alter your notation to conform with the standards `[r, c]` that are common in mathematics, statistics, and most if not all programming languages, including R. – lmo Aug 17 '17 at 18:24
  • Thank you all for your responses, and apologies, I confused the order of rows and columns. Your solution did it for me Alex P, thanks for the help! – Jess Aug 17 '17 at 18:31
  • @Jess did you know you can close this question by accepting Alex P's answer? (Check mark to the left of his answer) – CPak Aug 18 '17 at 02:10
  • I did not know that, thanks. – Jess Aug 18 '17 at 13:37

1 Answers1

1

For one thing, the data.frame subset goes like df[row,column] It seems like you might have that backwards. Second, I'm not sure why you are using cbind() within the brackets of a dataframe subset.

Here's how I might do it:

rows <- 1
for (i in 64:111) {
    Prod1[1:rows, i] <- 0
    rows = rows+1
}

Does that work for you?

Alex P
  • 1,574
  • 13
  • 28