-1

I'm working on a database of sensors

This is a subset of my data

1

I would like to calculate the duration of each 'ON' event for all my sensors. Knowing that the duration of an 'ON' is equal to the difference between the first ON and the first OFF For example in the table for sensor 'capteur1', I have to have 41 seconds, 30 seconds, 25 seconds, etc. Thank,

talat
  • 68,970
  • 21
  • 126
  • 157
  • 2
    Please don't post images of data, it's not very useful. Instead, create a text-based reproducible example – talat Jun 15 '18 at 08:44

1 Answers1

0

short code - give it a try:

# important - time must be a time-element (strptime or use format for example)

# subset only ON and OFF
ON <- df$time[df$capteur1 %in% "ON"]
OFF <- df$time[df$capteur1 %in% "OFF"]

# Create tempoary element to append to in for-loop
temp <- NULL # temp stands for temporary
name_temp <- NULL

# Loop over ON-Elements
for (i in ON) {
    a <- difftime(OFF, i, units = "sec") # difftime of i-element of ON vs all OFF
    a <- a[!a < 0] # drop negative seconds as Off was before on
    # append positive Seconds - but only the first element - as this was the next OFF
    temp <- c(temp, a[1])
    name_temp <- c(name_temp, as.character(i))
    }

# Give names to elements
names(temp) <- name_temp

# show temp
temp

Hope this helps

Sebastian

Sebastian Bloy
  • 101
  • 1
  • 9