Selecting rows in R based on condition

Viewed 13

I have a dataframe grouped by ID1, ID2, ID3 and variables V1, V2, V3 and V4. I am trying to capture values per group in R which are most different from median. For this, I have subtracted median from each value and squared that (bc there are some with negative values). Below is an example dataframe.

colnames <- c("ID1", "ID2", "ID3", "V1", "V2", "V3", "V4")

a <- c("A", "B", "C", "D")
b <- c("X", "Y", "Z", "T")
c <- c("1", "2", "3", "4")
d <- c(1.23,2.03,2.45,5.66)
e <- c(1,2,3,4)

df <-data.frame(a,b,c,d,e)

I have made a function med_removed as follows. 

med_removed <- function(x, na.rm = TRUE, ...) {
  mad <- sort((x- median(x, na.rm = T))^2)
  y <- head(mad, 4)  
  y
}

df_selected <- df%>% group_by(ID1 ID2,ID3) %>%mutate_all(., med_removed)

The problem is that I want to select rows in the original dataframe based on the (x-median(x))^2 to pick up the top 2 values.

Does anyone know a good way of doing that.

Thanks

0 Answers
Related