Home > Net >  How to compute multiple looping and if conditions for a Data Frame?
How to compute multiple looping and if conditions for a Data Frame?

Time:12-03

I have a data like this below, and if you see the formula in excel, it compares every second element in row with the first element in the if statement.

In the first condition it compares 2nd and 1st element of the key & 2nd and 1st element of Year_Month and computes the AND logic. If it turns as True then checks 2nd and 1st element of Date if they are equal then, keep the date as it is otherwise Subtract the 2nd element with the first. If the entire condition doesn't match then no value should be passed.

I have pasted 6 rows here. Like this I have plenty of rows in my data frame. How to write the script for a situation like this?

enter image description here

CodePudding user response:

I think you're asking if you can go through the rows of the data and check if every second element is equal to every first element?

If so the way that I would go about this programmatically is to loop through the rows in a step:

data=data.frame(Date=c(1,1,2,4,4),Time=c(2,2,3,4,4))
as_far_as=nrow(data)-1
for(i in 1:as_far_as){
     print(data$Date[i])
     print(data$Date[i 1])
 }
[1] 1
[1] 1
[1] 1
[1] 2
[1] 2
[1] 4
[1] 4
[1] 4
as_far_as=nrow(data)-1
for(i in 1:as_far_as){
    print(data$Date[i])
    print(data$Date[i 1])
}

Above I am looping through the rows and asking it to print every first element (data$Date[i]) and then every second element (data$Date[i 1])

If I want to introduce boolean logic into this I would do:

as_far_as=nrow(data)-1
for(i in 1:as_far_as){
    if(data$Date[i]==data$Date[i 1] & data$time[i]==data$time[i 1]){
         print('dates are the same')
    }else{
         data$Date[i]=data$Date[i]-data$Date[i 1]
    }
}

I can't really get a sense of what exactly you're asking as I don't do excel but try playing with the code above and if statements if(x==y){...}else{...} to get what you want.

CodePudding user response:

This piece of code has solved my problem

for(i in 1:nrow(Data)){
  if(Data$Key[i]==Data$Key[i 1] & Data$Month_Year[i]==Data$Month_Year[i 1]){
    Data$Condition[i]="True"
  }else {
    Data$Condition[i]="False"
  }
}


for(j in 1:nrow(Data)){
  if(Data$Condition[j]=="True"){
    if(Data$Date[j]==Data$Date[j 1]){
      Data$Lead.Time[j]=0
    }else{
      Data$Lead.Time[j]= Data$Date[j 1]-Data$Date[j]
    }
    
  }else {
    Data$Lead.Time[j]=0
  }
}
  • Related