lundi 29 janvier 2018

"missing value where TRUE/FALSE needed" but no NA in data? In r

I have two dataframes.

data1:

ThirtyWestTime            Direction    Period
2017-03-20 19:19:00         W            0
2017-03-20 08:44:51         E            0
2017-03-20 12:09:22         W            0

times:

Direction      DateAct              DateDe              period
  E        2017-03-20 01:00:00   2017-03-20 08:00:00     2344
  W        2017-03-20 11:30:00   2017-03-20 19:00:00     2345

I am trying to loop through each row in data1 to see if data1$Direction matches times$Direction, if data1$ThirtyWestTime is greater or equal to times$DateAct and if data1$ThirtyWestTime is smaller or equal to times$DateDe. If all these rules are satisfied it should take the corresponding period in times, or be zero. Hence I want the following:

data1:

ThirtyWestTime            Direction     Period
2017-03-20 19:19:00         W            0
2017-03-20 08:44:51         E            0
2017-03-20 12:09:22         W            2345

I have used the following loop but it gives me the following error:

for (j in 1:nrow(data1)){
  for (i in 1:nrow(times)){
    if ((data1$ThirtyWestTime[j]<=times$DateDe[i]) && (data1$ThirtyWestTime[j]>=times[i,2]) && identical(data1$Direction[j],times[i,1])){
  data1$Period[j]<-times[i,4]
} else {data1$Period[j]<-data1$Period[j]} 
  } 
}

Error in if ((data1$ThirtyWestTime[j] <= times$DateDe[i]) && (data1$ThirtyWestTime[j] >=  : 
  missing value where TRUE/FALSE needed

I have removed all NAs from my data so I don't know why this error is coming up and the loop breaks on j=2.

Please help. Thank you

Aucun commentaire:

Enregistrer un commentaire