R: Number of obs between min and max -
i need extract number of observations between min , max. know can subset data, creating new df calculate length interested in less involved process. example, have , number of observations min max,
ddd <- mydf[,list(minvar1 = min(var1, na.rm=true), maxvar1 = max(var1, na.rm=true)), by="group"]
is there direct approach without intermediate df? thanks.
edit: guess bit more complicated stated. group = 1, minimum value 2 need minimum indexed lower max value index/position. so, range 3 7 length of 3. idx variable scores measured index/position of var1. so, max position of var1 must first identified, insure min position extracted idx less of max position.
group var1 idx 1 3 4 1 5 5 1 7 6 1 3 7 1 2 8 2 5 12 2 6 13 2 9 14 2 11 15 2 5 16 group min max length 1 3 7 3 2 5 11 4
by using data.table
, expected output. convert 'data.frame' 'data.table' (setdt(df1)
). grouped 'group', order
'idx', position of maximum value of 'var1' ('ind'), position of minimum value of 'var1' lower 'ind' ('ind2'). summarise , create columns 'min' , 'max' indexing 'ind2' , 'ind' on 'var1' while 'length' created taking difference of 'idx' using same 'ind', 'ind2' , adding 1.
library(data.table) setdt(df1)[order(idx), {ind <- which.max(var1) ind2=which.min(var1[seq(ind)]) list(min=var1[ind2], max=var1[ind], length=idx[ind]-idx[ind2]+1)} , group] # group min max length #1: 1 3 7 3 #2: 2 5 11 4
Comments
Post a Comment