Force rows to get a certain value on a dummy

Viewed 48

I have a dataframe (lmr_sak) with verdicts from criminal cases in the Norwegian Court of Appeals from 1993-2019. On the 1st of October in 2015 a new criminal law (Straffeloven 2005 [not a typo, it took 10 years to come in to force]) replaced the old one from 1902.

I want to create a dummy for whether a verdict utilized the old or new law. First, I created a dummy based on the dates:

lmr_sak$dato <- as.Date.factor(lmr_sak$dato)


lmr_sak <- lmr_sak %>% 
  mutate(strl1902 = ifelse(dato > "1993-01-04" & dato < "2015-10-01",1,0))

But the problem is that some of the verdicts after 2015-10-01 still used the old law (because the alleged crimes were committed before 2015-10-01), resulting in verdicts getting the wrong values on 'strl1902'.

Luckily, in my df I have a column 'paragraf' which I think can help remedy the problem. Examples of its contents are:

  • 'Straffeloven (1902) §99'
  • 'Straffeloven (2005) §93'
  • 'Straffeloven 1902 §9'
  • 'Straffeloven 2005 §77'

What I wish to do is to force the rows with the strings (1902) or 1902 to get 1 on 'strl1902', and rows with (2005) or 2005 to get 0.

I imagine that I can do it with piping the code above, and maybe use ifelse(), replace() and a form of regex, but I'm very uncertain of what to do...

ANSWER:

Thanks to @Skaqqs suggestion, this ifelse with multiple logic did the trick:

lmr_sak_match$strl1902 = ifelse(lmr_sak_match$dato > "1993-01-04" & lmr_sak_match$dato < "2015-10-01", 1,
                                ifelse(grepl("1902", lmr_sak_match$paragraf),1,0))
2 Answers

I suggest using a regular expression, like this:

lmr_sak$strl1902 <- grepl(pattern = "Straffeloven.*1902", x = lmr_sak$paragraf)

If you want to include date in your logic as well, you can do so like this:

lmr_sak$strl1902 <- (lmr_sak$dato > "1993-01-04" & lmr_sak$dato < "2015-10-01") &
  grepl(pattern = "Straffeloven.*1902", x = lmr_sak$paragraf)

And you can wrap this in an ifelse() if you wish to use 1 and 0 as values for your dummy variable.

lmr_sak$strl1902 <- ifelse(
    test = (lmr_sak$dato > "1993-01-04" & lmr_sak$dato < "2015-10-01") &
        grepl(pattern = "Straffeloven.*1902", x = lmr_sak$paragraf),
    yes = 1, 
    no = 0)

This ifelse with multiple logic did the trick:

lmr_sak_match$strl1902 = ifelse(lmr_sak_match$dato > "1993-01-04" & lmr_sak_match$dato < "2015-10-01", 1,
                                ifelse(grepl("1902", lmr_sak_match$paragraf),1,0))

Related