0

I have a df that has several columns including one column with a range of values from 0 to around 100:

> df$days_fract

1] 0.000000000 0.006944444 0.013888889 0.020833333 0.027777778 0.034722222

Based on the value, I want to loop through multiple if-statements to create a new column which contains a string labelling the cycle number:

df$cycle <- ifelse(df$days_fract < 0.5 , "cycle0",
 ifelse(df$days_fract >= 0.5 & df$days_fract < 1.5 , "cycle1",
  ifelse(df$days_fract >= 1.5 & df$days_fract < 2.5 , "cycle2",
   ifelse(df$days_fract >= 2.5 & df$days_fract < 3.5 , "cycle3",
    ifelse(df$days_fract >= 3.5 & df$days_fract < 4.5 , "cycle4",NA)))))

However, since df$days_fract is quite long, this isn't very handy at all. Basically, I want to loop through it somehow (or other ideas very welcome) where each cycle ranges from 1.5-2.5, 2.5-3.5, 3.5-4.5 and so on.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
bma
  • 13
  • 2

1 Answers1

3

Instead of using multiple ifelse statements, an option is cut

with(df, cut(days_fract, breaks = c(-Inf, 0.5, 1.5, 2.5, 3.5, 4.5),
       labels = paste0("cycle", 0:4)))
akrun
  • 874,273
  • 37
  • 540
  • 662