Home > Software engineering >  How to select dataframe in R filter max( ) min( ) and conditional value?
How to select dataframe in R filter max( ) min( ) and conditional value?

Time:05-25

I have this little fragment of a dataframe:

A B C D E
... ... ... ... ...
10 .B. 41.32 5.00e-02 28
10 .C. 41.26 5.08e-02 28
10 .X. 42.43 2.13e-01 36
9 .A. 41.07 5.23e-02 28
9 .A. 41.07 5.28e-02 28
8 .X. 38.97 8.13e-02 28
... ... ... ... ...
res<-data.frame(year = c(10L,10L, 10L, 10L, 10L, 10L), c.col = c("B","C", "A", "A", "A", "X"), chisq = c(41.32,41.26, 42.43, 41.07, 41.08, 38.97), p.value = c(5.00e-02,5.08e-02, 2.13e-01, 5.23e-02, 5.28e-02, 8.13e-02),  df = c(26,28, 36,28, 28, 28))

#this filter is not working, what is the correct way to do it?
res %>%  dplyr::group_by(year) %>% dplyr::filter(res$year==10 & min(p.value) & max(df))

Expected output:

A B C D E
10 .X. 42.43 2.13e-01 36

CodePudding user response:

If you want to conditionally select the row with the min and max, you can use the following code:

res %>%  
  dplyr::group_by(year) %>% 
  dplyr::filter(year==10 & p.value == min(p.value) & df == max(df))

Please note that in your example res, there is no row with the min & max value.

  •  Tags:  
  • r
  • Related