How to separate a vector based on conditions in R

岁酱吖の 提交于 2019-12-11 06:58:20

问题


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"
                                            )
                    )


来源:https://stackoverflow.com/questions/44285151/how-to-separate-a-vector-based-on-conditions-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!