0

I am trying to turn Failures_Avg from continuous into a factor of 3 levels.

Use <- read_csv("FinalData.csv")%>% filter(Week %between% c("1", "7")) %>% dplyr::select(-c(LactationNumber,DaysPerWeek, TotalWeeks))%>% mutate_at(vars(Farm,Parity,CowNr,Week,Failures_Avg), as.factor)%>% mutate_at(vars(Milk_AvgDay,Milk_AvgVisit,IntervalCV), as.numeric)%>% group_by(Farm,CowNr)

Here I read in failures_Avg as a categorical variable but since it is continuous there are about 65 levels. I am trying to change it from this into

Low - =0

Med - Between 0 & including 1

High - Greater than 1

Thank you in advance

Swart205
  • 1
  • 1

1 Answers1

2

We can use cut

library(dplyr)
Use %>%
   mutate(failures_Avg = cut(failures_Avg, breaks = c(-Inf, 0, 1, Inf), labels = c("Low", "Med", "High")))

or case_when

Use <- Use %>%
     mutate(failures_Avg = case_when(failures_Avg == 0 ~ "Low",
                 (failures_Avg > 0 & failures_Avg < 1) ~ "Med",
                   TRUE ~ "High"))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • will this have low being solely zero and med including 1 or will it be right below 1 and/or will this be including 0? – Swart205 Jul 08 '21 at 17:37
  • @Swart205 If you are using `dplyr::between`, it is a shortcut for `x >= left & x <= right` , but you can make this more specific, by changing it to `failures_Avg > 0 & failures_Avg < 1` in the code – akrun Jul 08 '21 at 17:38
  • Use <- read_csv("FinalData.csv")%>% filter(Week %between% c("1", "7")) %>% dplyr::select(-c(LactationNumber,DaysPerWeek, TotalWeeks))%>% mutate_at(vars(Farm,Parity,CowNr,Week,Failures_Avg), as.factor)%>% mutate_at(vars(Milk_AvgDay,Milk_AvgVisit,IntervalCV), as.numeric)%>% group_by(Farm,CowNr) %>% mutate(Failures_Avg = case_when(Failures_Avg == 0 ~ "Low", between(Failures_Avg, >0, <=1) ~ "Med", TRUE ~ "High")) – Swart205 Jul 08 '21 at 17:46
  • I tried doing this and then received Error: unexpected ')' in " TRUE ~ "High")" – Swart205 Jul 08 '21 at 17:47
  • I meant to remove the `between` if use `(failures_Avg > 0 & failures_Avg < 1) ~"Med",` – akrun Jul 08 '21 at 17:47
  • @Swart205 try the update one in my post – akrun Jul 08 '21 at 17:48