Q:

R-Changing row values based on a value specified by a column

I have the dataset(df) below.  The column "Num" represents the number of column in each row that need its value changed to 5. 
Col1    Col2    Col3    Col4    Col5    Col6    Col7    Num
0        1       1      1       1       0       0       3
0        0       1      1       1       1       1       3
0        0       0      1       1       1       0       2
0        0       0      1       0       1       0       5
1        1       1      1       1       1       1       6

My resulting dataset would look like this:
Col1    Col2    Col3    Col4    Col5    Col6    Col7    Num
    5        5       5      1       1       0       0       3
    5        5       5      1       1       1       1       3
    5        5       0      1       1       1       0       2
    5        5       5      5       5       1       0       5
    5        5       5      5       5       5       1       6

I used the following command, but it only changes the values based on the first row of column. 
for (i in 1:length (df$Num)){
                 df[,1:i]=5
         }

If someone could point out what I am doing wrong, I would really appreciate it.  

A:

Try
df[cbind(rep(1:nrow(df), df$Num), sequence(df$Num))] <- 5   
df
#  Col1 Col2 Col3 Col4 Col5 Col6 Col7 Num
#1    5    5    5    1    1    0    0   3
#2    5    5    5    1    1    1    1   3
#3    5    5    0    1    1    1    0   2
#4    5    5    5    5    5    1    0   5
#5    5    5    5    5    5    5    1   6

data
df <- structure(list(Col1 = c(0L, 0L, 0L, 0L, 1L), Col2 = c(1L, 0L, 
0L, 0L, 1L), Col3 = c(1L, 1L, 0L, 0L, 1L), Col4 = c(1L, 1L, 1L, 
1L, 1L), Col5 = c(1L, 1L, 1L, 0L, 1L), Col6 = c(0L, 1L, 1L, 1L, 
1L), Col7 = c(0L, 1L, 0L, 0L, 1L), Num = c(3L, 3L, 2L, 5L, 6L
)), .Names = c("Col1", "Col2", "Col3", "Col4", "Col5", "Col6", 
 "Col7", "Num"), class = "data.frame", row.names = c(NA, -5L))

A:

If you want for-loop solution, it is 
for (i in 1:length (df$Num)){
    df[i,1:df$Num[i]]=5
}

