简体   繁体   中英

For loop not iterating through columns r

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
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM