0

I've been trying to run my R script unsuccessfully.

What I don't understand is that I was able to run it for other files, but not for this one.

The purpose of the code is to add 1 to "num" every time the timeshift of "Date.time" column is more than 10 minutes.

So here is the code:

#Exemple of data.frame from where I started
data <- data.frame(Day=c(13,13,13,13,12), Month=c("05","05","05","05","06"),Year=c(2009,2009,2009,2009,2009), Time=c("15:13","15:23","15:33","17:53","17:24"),num=c(1,1,1,1,1))

#Creation of column "Date" to merge columns "Day", "Month", "Year" together. Then merging "Date" and "Time" in the "Date.time" column. 
data$Date <- paste(synchro$Day,synchro$Month,synchro$Year, sep="/")
data$Date.time <- paste(synchro$Date, synchro$Time, sep=" ") 

#Change format of "Date.time" with as.POSIXct, so it's considered as a time column.
synchro$Date.time <- as.POSIXct(synchro$Date.time,format="%d/%m/%Y %H:%M",tz="")

#Then try the "if" statement to add 1 everytime the timeshift in column "Date.time" is more than 10 minutes.

for(i in 2:nrow(synchro)) 
{if(as.numeric(synchro$Date.time[i] - synchro$Date.time[i-1])!=10)  
{synchro$num[i] = (synchro$num[i-1])+1} 
  else{synchro$num[i] = synchro$num[i-1]}
}

#Should return something like this:
data <- data.frame(Day=c(13,13,13,13,12), Month=c("05","05","05","05","06"),Year=c(2009,2009,2009,2009,2009), Time=c("15:13","15:23","15:33","17:53","17:24"),num=c(1,1,1,2,3))

I tried to change the format of Date.time column but it always returns the following error message:

Error in if (as.numeric(synchro$Date.time[i] - synchro$Date.time[i - 1]) != : missing value where TRUE/FALSE needed

Can someone help me find the problem with my code please?!

Thank you in advance!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. How many rows of data are in the file that doesn't work? Is it more than 1? – MrFlick Mar 28 '20 at 21:36
  • The error message tells you that you have a missing value in your `if` statement. That is either `data$Date.time[i]` or `data$Date.time[i-1]` is a missing value. You don't need a loop for this. A simple `ifelse()` statement should handle it. – dcarlson Mar 29 '20 at 04:08
  • MrFlick, I add an example. I hope it is clearer this way! And about the ifelse, I thought I had to use the "for" because I want to add 1 to the precedent number. If I only use the ifelse statement, it would not considered that the number has change. – Andréanne Girard-Lemieux Mar 30 '20 at 18:08

0 Answers0