0

I would like to assign category labels based on rowID. Basically, I have a dataset that spans 23 hours tracking the movement of zebrafish larvae and I want to indicate that the 5 minutes period after the larvae is placed in the machine and the 5 minutes period after light condition changes (light to dark, dark to light etc.) is considered a "HABITUATION" period. Movement in any other times is considered a "NON-HABITUATION" period. I have assigned a rowID to every single second of data in the data frame and are using the row-ID ranges to indicate "HABITUATION" periods and "NON-HABITUATION" periods. However my code doesn't work- I keep getting this error " Error in if (as.numeric(data_long$rowID) > 37650 & as.numeric(data_long$rowID) < : the condition has length > 1".

What am I doing wrong?

Please see my code below, thank you very much!

enter code heredata_long$CONDITIONS_2<- ifelse(as.numeric(data_long$rowID) <301){
      print("HABITUATION")
    } else{
      if(as.numeric(data_long$rowID) > 37650 & as.numeric(data_long$rowID) < 37952){
        print("HABITUATION")
      } else{
        if(as.numeric(data_long$rowID) > 71880 & as.numeric(data_long$rowID) < 72182){
          print("HABITUATION")
        }
        else{
          print("NOT HABITUATION")
        }
      } 
  • 2
    You are mixing the vectorized `ifelse()` and the non-vectorized `if() {} else {}`. They are very different. `if` only works on single elements, not long vectors. You want all `ifelse` here. (Though perhaps `dplyr::case_when` would be nicer) – Gregor Thomas Oct 12 '22 at 19:48
  • Also, you would make your code simpler if you converted your rowID to numeric one time, before all this: `data_long$rowID <- as.numeric(data_long$rowID)`. Then you don't have to keep repeating it inside every `ifelse`. – Gregor Thomas Oct 12 '22 at 19:49
  • Turning this into `data_long$rowID <- as.numeric(data_long$rowID)` followed by `data_long$CONDITIONS_2<- ifelse(data_long$rowID <301, "HABITUATION", ifelse(data_long$rowID > 37650 & data_long$rowID < 37952, "HABITUATION", ifelse(data_long$rowID > 71880 & data_long$rowID < 72182, "HABITUATION", "NOT HABITUATION")))` – Gregor Thomas Oct 12 '22 at 19:53
  • Or more simply `data_long$CONDITIONS_2 <- with(data_long, ifelse(rowID < 301 | (rowID > 37650 & rowID < 37592) | (rowID > 71880 & rowID < 72182), "HABITUATION", "NOT HABITUATION"))` – Gregor Thomas Oct 12 '22 at 19:54
  • 1
    Thank you so much! This has been immensely helpful! – Sheeraja Sridharan Oct 13 '22 at 20:59

0 Answers0