rmultirow

How do I do a multirow formula?


I am trying to use a multirow formula to have a new calculated column but can't quite figure it out.

Suppose I my data is this:

x     y

1     2

1     2

1     6

1     7

2     4

2     5

2     9

I want to create a calculated column z in which would have the following logic:

If the value of x is equal to the previous value of x then y-previous(x) else 0.


Solution

  • Try this:

    # load package
    library(dplyr)
    # reproduce your data
    df <- data.frame(x = rep(1:2, c(4, 3)),
                     y = c(2, 2, 6, 7, 4, 5, 9))
    df %>%
      mutate(z = case_when(x == lag(x) ~ y - lag(x),
                           TRUE ~ 0))
    

    Hope it helps