Vineet Goti
Vineet Goti

Reputation: 207

Setting the values of some rows by if function within a for loop in r

After a condition is met, I want to set a specific value in column for a specific number of number of rows.

my data looks like this:

mydat1 <- data.frame(ID=rep(1,20),VID=c(rep(0,12),1,rep(0,7)),FLAG =c(rep(0,12),1,rep(0,7)),DT=rep(0,20))
mydat2 <- data.frame(ID=rep(2,20),VID=c(rep(0,7),1,rep(0,12)),FLAG =c(rep(0,7),1,rep(0,12)),DT=rep(0,20))

test <- rbind(mydat1,mydat2)

I want it to look like this:

repdat1 <- data.frame(ID=rep(1,20),VID=c(rep(0,12),1,rep(0,7)),FLAG =c(rep(0,12),1,rep(0,7)),DT=c(rep(0,12),rep(2,8)))
repdat2 <- data.frame(ID=rep(2,20),VID=c(rep(0,7),1,rep(0,12)),FLAG =c(rep(0,7),1,rep(0,12)),DT=c(rep(0,7),rep(2,8),rep(0,5)))

wantdat <- rbind(repdat1,repdat2)

So what I am trying to accomplish is, for a particular row, if VID and FLAG columns are both equal to 1, then I want the DT column for that row and the subsequent seven rows to be 2.

I am using an iffunction within a for loop as follows:

for(i in 1:nrow(test)) {

if (test$VID[i]==1 & test$FLAG[i]==1) {
test$DT[i] <- 2
test$DT[i:i+7] <- 2
  }

}

when I do this, I only set DT=2 when VID=1 & FLAG=1 and for the seventh row after this condition is met. The rows in between do not get set to 2.

The object wantdat above shows what I am trying to accomplish.

Appreciate your help.

Upvotes: 1

Views: 42

Answers (2)

akrun
akrun

Reputation: 887148

Here is an option with data.table

library(data.table)
ind <- setDT(test)[, {i1 <- .I[VID == 1 & FLAG == 1]
       unique(i1 + rep(seq_len(7), length(i1)))}]
test[ind, DT := 2]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

We can first find out indices where the condition is satisfied, then create a sequence of next 7 indices and replace those with 2.

inds <- which(test$VID == 1 & test$FLAG == 1)
test$DT[c(mapply(`:`, inds, inds + 7))] <- 2

test
#   ID VID FLAG DT
#1   1   0    0  0
#2   1   0    0  0
#3   1   0    0  0
#4   1   0    0  0
#5   1   0    0  0
#6   1   0    0  0
#7   1   0    0  0
#8   1   0    0  0
#9   1   0    0  0
#10  1   0    0  0
#11  1   0    0  0
#12  1   0    0  0
#13  1   1    1  2
#14  1   0    0  2
#15  1   0    0  2
#16  1   0    0  2
#17  1   0    0  2
#18  1   0    0  2
#...

Upvotes: 3

Related Questions