R-function which

I am trying to make a data block with the maximum number of records at a time. I need a data frame with 4 rows (one for each G) with max for X in this group and the corresponding value of Y. I know that I could write a loop, but would prefer.

Data<-data.frame(X=rnorm(200), Y=rnorm(200), G=rep(c(1,2,3,4), each=50))
XMax<-tapply(Data$X, Data$G, function(x){max(x, na.rm=T)})
WhichXMax<-tapply(Data$X, Data$G, function(x){which.max(x)})

The which.max function returns the row number after the data was a subset with a tapply coefficient, where I really want the row number to refer to the rows of data. So I could do something like:

YMax<-Data$Y[Which]
MaxData<-data.frame(XMax=XMax, YMax=YMax, G=levels(Data$G))
+4
source share
3 answers

You can use byand refer to the rownamesstring returned which.max:

Data[by(Data, Data$G, function(dat) rownames(dat)[which.max(dat$X)] ),]

#           X          Y G
#4   1.595281 -0.3309078 1
#61  2.401618  0.9510128 2
#147 2.087167  0.9160193 3
#171 2.307978 -0.3887222 4

(This suggests set.seed(1)for reproducibility)

+6
source
library(dplyr)
Data %>% 
    group_by(G) %>% 
    filter(X==max(X))

If you do not want to include links, then

Data %>%
    group_by(G) %>%
    arrange(desc(X)) %>%
    slice(1)
+7
  library(data.table)
  set.seed(1)
  Data<-data.frame(X=rnorm(200), Y=rnorm(200), G=rep(c(1,2,3,4), each=50))
  setDT(Data)[,list(X=max(X),Y=Y[which.max(X)]),by=G]
   G        X          Y
1: 1 1.595281 -0.3309078
2: 2 2.401618  0.9510128
3: 3 2.087167  0.9160193
4: 4 2.307978 -0.3887222
+5

All Articles