简体   繁体   中英

Comparing consecutive rows in R, showing if they are increasing or decreasing

So I have respiration data that look something like this:

   Time      Resp
1  344.56   .003423
2  346.36  -.002452
3  348.43   .005053
4  350.64  -.006432
5  352.65   .008543
6  354.12  -.003654

Using R, I would like to mark when there are points of inhalation vs. exhalation, ie, points of positive-going values and negative-going values between each row.

For example, row1 to row2 has negative-going Resp (.003423 to -.002452), so I'm trying to figure out a way to show that Time 344.56 to Time 346.36 = "Exhalation" (negative going). Row2 to row3 would show that Time 346.36 to time 348.43 = "Inhalation" (positive-going), and so on.

I've looked across stackexchange and other websites, and tried various functions like rep and seq (and an attempt with dplyr ), but I've had no luck (frankly, I haven't used R in a few years).

Any insight on this problem would be great.

Thanks!

Is this what you are looking for?

library(dplyr)

df %>%
        mutate(Col = ifelse(Resp - lag(Resp) >= 0, "Inhalation", "Exhalation"))
# A tibble: 6 x 3
   Time     Resp Col       
  <dbl>    <dbl> <chr>     
1  345.  0.00342 NA        
2  346. -0.00245 Exhalation
3  348.  0.00505 Inhalation
4  351. -0.00643 Exhalation
5  353.  0.00854 Inhalation
6  354. -0.00365 Exhalation

DATA

df <- structure(list(Time = c(344.56, 346.36, 348.43, 350.64, 352.65, 
354.12), Resp = c(0.003423, -0.002452, 0.005053, -0.006432, 0.008543, 
-0.003654)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM