Error Message: Replacement has Length Zero

Error in dat$methrs[j] <- second_factor * second_position_time : 
  replacement has length zero

for (j in 1:length(dat$time)) {
  if (is.na(dat$methrs[j]) & (dat$wear_day[j] %in% good_days)) {
    mets <- dat$methrs[j - 1] / (dat$interval[j - 1] / 3600)
    first_position_time <- as.numeric(difftime(dat$time[j], dat$time[j - 1], 
                                               units = "hours"))
    second_position_time <- as.numeric(difftime(dat$time[j + 1], dat$time[j],
                                                units = "hours"))
    totaltime <- dat$interval[j - 1]
    first_factor <- (first_position_time / totaltime) * mets
    second_factor <- (second_position_time / totaltime) * mets
    dat$methrs[j - 1] <- first_factor * first_position_time
    dat$methrs[j] <- second_factor * second_position_time
  } else {
    dat$methrs[j] <- dat$methrs[j]
  }
}

Not sure what to do with this error message. I'm trying to build graphs from my data.

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Time Time(approx) Data Count Event Type Duration (s) Waking Day Cumulative Step Count Activity Score (MET.h) AbsSumDiffX AbsSumDiffY AbsSumDiffZ Time Upright (s) Time Upside Down (s) Time Back Lying (s) Time Front Lying (s) Time Left Lying (s) Time Right Lying (s)
44715.99929 6/3/2022 23:58 0 1 56412 1 0 21.938 894 1108 1335 56412 0 0 0 0 0
44716.65221 6/4/2022 15:39 564120 2 5.7 1 1 0.002938889 327 327 552 5.7 0 0 0 0 0
44716.65228 6/4/2022 15:39 564177 1 108456.4 1 1 42.17748889 813 1973 3522 108456.4 0 0 0 0 0
44717.90756 6/5/2022 21:46 1648741 2 2.5 1 2 0.001694444 144 57 103 2.5 0 0 0 0 0
44717.90759 6/5/2022 21:46 1648766 1 32437.4 1 2 12.61454444 591 1166 1618 32437.4 0 0 0 0 0
44718.28302 6/6/2022 6:47 1973140 2 5.4 1 3 0.002822222 520 325 337 5.4 0 0 0 0 0