简体   繁体   中英

combined and sum the data.frame within tolerance by using one of column

I am stuck with simple question. How to combine and mean the numbers within setting tolerance (diff = +-0.002) in ia column and sum the values in times column.

for example

 ia<-c(1.001,1.002,2,2.2,1.1,1,1,1,2.5,1,2.8)
 time<-c(4.5,2.4,1.5,1.2,4.9,6.4,4.4, 4.7, 7.3,2.3, 4.3)
 a<-as.data.frame(cbind(ia, time))

       ia time
   1  1.001  4.5
   2  1.002  2.4
   3  2.000  1.5
   4  2.200  1.2
   5  1.100  4.9
   6  1.000  6.4
   7  1.000  4.4
   8  1.000  4.7
   9  2.002  7.3
   10 1.000  2.3
   11 2.800  4.3

   to 

       ia time
   1  1.001  24.7    #  ia = mean(1 2 6 7 8 10)   time = sum(1 2 6 7 8 10)
   3  2.001  9.7     #  ia = mean(2 9)   time = sum(2 9)
   4  2.200  1.2
   5  1.100  4.9
   11 2.800  4.3

Thanks!

It's not clear to me at all what you're trying to do, and the examples/explanations you have given in the comments leave me scratching my head even more.

That aside, perhaps the following is a decent starting point for further refinements.

We can use cut to group values in ia and then summarise ia and time values by grp

diff = 0.002
library(dplyr)
a %>%
    mutate(grp = cut(ia, seq(min(ia), max(ia), by = diff), include.lowest = T)) %>%
    group_by(grp) %>%
    summarise(
        io = mean(ia),
        time = sum(time))
## A tibble: 6 x 3
#  grp            io  time
#  <fct>       <dbl> <dbl>
#1 [1,1.002]    1.00  24.7
#2 (1.098,1.1]  1.1    4.9
#3 (1.998,2]    2      1.5
#4 (2.198,2.2]  2.2    1.2
#5 (2.498,2.5]  2.5    7.3
#6 (2.798,2.8]  2.8    4.3

One solution is to make a dummy grouping variable. Unfortunately, it is hard to tell from your question what grouping you seek. Though based on your toy output, I am guessing you want {(0, 1.1) [1.1, 2.01) [2.01, 2.2) [2.2, 2.8) [2.8, Inf)}? If so you could use:

a$group <- ifelse(a$ia < 1.1, 0, 
   ifelse(a$ia >= 1.1 & a$ia < 2.01, 1, 
      ifelse(a$ia >= 2.01 & a$ia < 2.2, 2, 
         ifelse(a$ia >= 2.2 & a$ia < 2.8, 3, 4))))

Then you can use tidyverse functions more easily

a %>% group_by(group) %>% summarize("ia" = mean(ia), "time" = sum(time))

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