How to separate a vector based on conditions in R

2019-08-01 23:31发布

问题:

I have a dataframe with some event dates.

I used difftime to compute the delay between each event, but now I want to create a factor with each first event.

Here is my attempt :

dataframe$delay.event.A = difftime(dataframe$dateA, dataframe$dateStart, units = "days")
dataframe$delay.event.B = difftime(dataframe$dateB, dataframe$dateStart, units = "days")
dataframe$delay.event.C = difftime(dataframe$dateC, dataframe$dateStart, units = "days")
dataframe$delay.first.event = pmin.int(dataframe$delay.event.A, dataframe$delay.event.B, dataframe$delay.event.C, na.rm = TRUE)

dataframe$event.status = ifelse(
  dataframe$delay.first.event==dataframe$delay.event.A, "event A", ifelse(
    dataframe$delay.first.event==dataframe$delay.event.B, "event B", ifelse(
      dataframe$delay.first.event==dataframe$delay.event.C, "event C" , "no event"
)))

This is not working at all, like each ifelse is overwriting the previous one.

How can I do this ?

回答1:

Something like this may get you what you're looking for.

library(dplyr)

dataframe <- dataframe %>%
             mutate(event.status = case_when(.$first.event == .$delay.event.A
                                             ~ "event A",
                                             .$first.event == .$delay.event.B
                                             ~ "event B",
                                             .$first.event == .$delay.event.C
                                             ~ "event C",
                                             TRUE
                                             ~ "no event"
                                            )
                    )


标签: r r-factor