rdplyrdata.tablegroupinglabeling

Assigning label to each record based on multiple conditions


This is my df (data.frame)

Distance <- c(30, 20, 32, 20)
Speed <- c(25, 24, 17, 21)
df <-data.frame(Distance,Speed)
df
  Distance Speed
1       30    25
2       20    24
3       19    15
4       20    21

I need to label each row based on two conditions:

  1. If the distance = 20 and
  2. If the speed is greater than or equals to 18.

If condition satisfied label = "Danger" If condition not satisfied label = "Normal"

The desired output should look like this.

  Distance Speed  Label
   30    25 Normal
   20    24 Danger
   19    15 Normal
   20    21 Danger

Any way of doing this effectively?


Solution

  • You can use an if statement with your criteria and then transform the answer to the labels.

    library(dplyr)
    df <- df %>% mutate(Label = ifelse(Distance == 20 & Speed >= 18, 'Danger', 'Normal'))