Filtering a tibble into two tibbles based on if a column's value is increasing or decreasing

54 Views Asked by At

I am trying to filter a tibble into two tibbles. My data involves a column which is the variable (V) which is being controlled - so the data continously increases up to a value, and then decreases from that value. I would like to end up with one tibble with the part of the data for which V is increasing, and one tibble where V is decreasing. The point where the change happens can be filtered into the first data set. Filter items based on whether the amount is increasing or decreasing

But this doesn't really work for my problem - I want to filter the V values based on if they are higher or lower than the V value in the row before.

I tried:

rawfilt <- raw %>% 
    mutate(status=case_when(
    first(V) < last(V) ~ "Increasing",
    last(V) < first(V) ~ "Decreasing"))

But this just gives that everything is decreasing. (as the last value is lower than the first.

As an example data looks like:

t V
1 2
2 3
3 4
4 5
5 6
6 4
7 3
8 2

And I would liek to end up with:

Tibble 1:

t V
1 2
2 3
3 4
4 5
5 6

Tibble 2:

t V
6 4
7 3
8 2
1

There are 1 best solutions below

2
Isaac On

One alternative is doing the following using ifelse:

> data.frame(
+   't' = c(1, 2, 3, 4),
+   'v' = c(2, 3, 4, 3)
+ ) |> 
+   mutate(status = ifelse(t < v, "Increasing", "Decreasing")) 

  t v     status
1 1 2 Increasing
2 2 3 Increasing
3 3 4 Increasing
4 4 3 Decreasing

Other option using case_when:

> data.frame(
+   't' = c(1, 2, 3, 4),
+   'v' = c(2, 3, 4, 3)
+ ) |> 
+   mutate(status = case_when(t < v ~ "Increasing", 
+                             TRUE ~ "Decreasing")) 

  t v     status
1 1 2 Increasing
2 2 3 Increasing
3 3 4 Increasing
4 4 3 Decreasing