0

i have a dataframe that has 1000 rows and 4 columns where the dataframe has 100 ID's.

the dataframe looks like as follows:

 abc <- data.frame(ID = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2), 
              A = c(12,12.5,15,16,18,20,25,26,29,35, 12,12.5,15,16,18,20,25,26,29,35),
              B = c(20,19,18,17,16,20,25,28,30,35, 20,19,18,17,16,20,25,28,30,35),
              C = c(2,1,5,9,10,11,13,18,25,27,2,1,5,9,10,11,13,18,25,27))

here, the first condition is to select the minimum value from the 'B' column with respect to ID and select the corresponding A th column (i.e. for min(B) = 16, A = 18 for ID-1).

the second condition is to select the minimum value from the 'C' column with respect to ID and select the corresponding A th column (i.e. for min(C) = 1, A = 12.5 for ID-1)

finally, I would like to subset the data frame (from A = 12.5 to A = 18) with respect to ID

the expected/desired output data frame is as follows

 abcd <- data.frame(ID = c(1,1,1,1,2,2,2,2), 
              A = c(12.5,15,16,18,12.5,15,16,18),
              B = c(19,18,17,16,19,18,17,16),
              C = c(1,5,9,10,1,5,9,10))

i have tried the code as following

library(plyr)
e <- ddply(abc, .(ID), function(z) {
z[z$dmin(abs(z$C)) : min(abs(z$B)), ]
 })

but fails to get the desired output

Kumar
  • 157
  • 1
  • 13

2 Answers2

3

You can use which.min to get minimum value for C and B column and create a sequence between them to subset in slice for each ID.

library(dplyr)
abc %>% group_by(ID) %>% slice(which.min(C):which.min(B))

#    ID     A     B     C
#  <dbl> <dbl> <dbl> <dbl>
#1     1  12.5    19     1
#2     1  15      18     5
#3     1  16      17     9
#4     1  18      16    10
#5     2  12.5    19     1
#6     2  15      18     5
#7     2  16      17     9
#8     2  18      16    10
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
2

Here is a base R solution

abcd <- do.call(rbind,c(lapply(split(abc,abc$ID),function(x) x[which.min(x$C):which.min(x$B),]),make.row.names = FALSE))
ThomasIsCoding
  • 53,240
  • 4
  • 13
  • 45