Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine rows based on ranges in a column

Tags:

r

I have a pretty large dataset where I have a column for time in seconds and I want to combine rows where the time is close (range: .1-.2 seconds apart) as a mean.

Here is an example of how the data looks:

BPM seconds
63.9 61.899
63.9 61.902
63.8 61.910
62.1 130.94
62.1 130.95
61.8 211.59
63.8 280.5
60.3 290.4  

So I would want to combine the first 3 rows, then the 2 following after that, and the rest would stand alone. Meaning I would want the data to look like this:

BPM seconds
63.9 61.904
62.1 130.95
61.8 211.59
63.8 280.5
60.3 290.4 
like image 273
Mary Smirnova Avatar asked Oct 02 '18 07:10

Mary Smirnova


People also ask

How do I automatically merge rows in Excel?

Click the first cell and press Shift while you click the last cell in the range you want to merge. Important: Make sure only one of the cells in the range has data. Click Home > Merge & Center. If Merge & Center is dimmed, make sure you're not editing a cell or the cells you want to merge aren't inside a table.


1 Answers

We need to create groups, this is the important bit, the rest is standard aggregation:

cumsum(!c(0, diff(df1$seconds)) < 0.2)
# [1] 0 0 0 1 1 2 3 4

Then aggregate using aggregate:

aggregate(df1[, 2], list(cumsum(!c(0, diff(df1$seconds)) < 0.2)), mean)
#   Group.1         x
# 1       0  61.90367
# 2       1 130.94500
# 3       2 211.59000
# 4       3 280.50000
# 5       4 290.40000

Or use dplyr:

library(dplyr)

df1 %>% 
  group_by(myGroup = cumsum(!c(0, diff(seconds)) < 0.2)) %>% 
  summarise(BPM = first(BPM),
            seconds = mean(seconds))
# # A tibble: 5 x 3
#   myGroup   BPM seconds
#     <int> <dbl>   <dbl>
# 1       0  63.9    61.9
# 2       1  62.1   131. 
# 3       2  61.8   212. 
# 4       3  63.8   280. 
# 5       4  60.3   290. 

Reproducible example data:

df1 <- read.table(text = "BPM seconds
                  63.9 61.899
                  63.9 61.902
                  63.8 61.910
                  62.1 130.94
                  62.1 130.95
                  61.8 211.59
                  63.8 280.5
                  60.3 290.4", header = TRUE)
like image 82
zx8754 Avatar answered Sep 29 '22 14:09

zx8754