Jimena Paz
Jimena Paz

Reputation: 11

How can I add a column that sorts the last "n" values?

I have a data frame with columns Active and Cycles. I want to add a third column called state which is classified according to the number of cycles.

For example: for the first 20 that the state of Normal goes, for the last 20 "emergency "and for the rest" normal "

I have tried creating data frame for the last and first values and then joining them but it is cumbersome and I can't figure out how to place the label on the middle data.

df  <-  data_frame %>% 
         group_by(ACT) %>%
           top_n(20)
df=mutate(df, Fault = "EMERGENCIA")

It occurred to me that with ifelse it would be easier but I don't know what to put in the last condition.

Dt <- data_frame %>%
  group_by(ACT) %>%
  mutate(Faul = ifelse(CYCLE <= 20 , "Normal", 
                        ifelse(20 < CYCLE & CYCLE < ???????, "alerta", "emergencia")))

Upvotes: 1

Views: 43

Answers (1)

Cettt
Cettt

Reputation: 11981

You can try case_when to distinguish the cases:

data_frame %>%
  mutate(Faul = case_when(CYCLE <= 20 ~ "Normal",
                          CYCLE <= 40 ~ "alerta",
                          TRUE ~ "emergencia"))

Upvotes: 1

Related Questions