Filtering rows by multiple ranges

Hi there

I'm wondering how to filter and summarise the following DF using a single line code into a new dataframe (DF1). In other words, how to filter different row ranges (separately) for each column nomenclature (group A and B) and returning the mean.for each sub group.
So far, thats what I have found:

DF1<-DF %>% Filter(between(VALUE, 1,3) %>% summarise(meanVALUE=mean(VALUE))

Nevertheless it will return the mean for the first sub group only (values 1,2,3). How to consider the remaining groups within the filter?

| GROUP | VALUE |

|A| |1|
|A| |2|
|A| |3|

|A| |4|
|A| |5|
|A| |6|

|B| |7|
|B| |8|
|B| |9|

|B| |10|
|B| |11|
|B| |12|

Any help is very appreciated.

Thanks!

Sorry, I don't understand what you're trying to do. It would help if you a) formatted the example data so it's easier to read and, more important, b) showed your desired output for the example data.

use a group_by() and specificy GROUPas the grouping variable between your filter() and your summarise() function calls

Hi there. Thanks for the prompt reply. I had already tried using group_by, however, for the same group (lets say , group A) there are two ranges or subsets (1:3) and (4:6). I need the mean values for these subsets separately. The ideia is pretty easy, but getting this piped into a single line code is the point.

library(tidyverse)
df <- data.frame(GROUP=c(rep("A",3),rep("B",9)),
                         VALUE = 1:12)

df$VALUEm <- df$VALUE %% 3

df <- group_by(df,
               VALUEm)%>%mutate(newkey=row_number()) %>% 
  group_by(GROUP,newkey) %>% summarise(meanv=mean(VALUE))

  GROUP newkey meanv
  <fct>  <int> <dbl>
1 A          1     2
2 B          2     5
3 B          3     8
4 B          4    11

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.