I am trying to find the max value of a group and the associated row information for that max value where there are different groups repeated.
For example, the dataset looks as follows:
newid sex visitnum sbpval
36 13580 M 2 NA
37 13580 M 3 124
38 13580 M 4 116
39 21525 F 2 410
40 21525 F 3 116
I would like the output to look like this:
newid sex visitnum sbpval
1 13580 M 3 124
2 21525 F 2 410
I am trying to create a loop that loops through but is having a hard time figuring out how to group them.
This is the code I have so far:
> for (i in 1:length(df)){
+ maxsbp = max(i, na.rm = F)
+ max = cbind(maxsbp,max)
+ result = cbind(result, df[[i]])
+ }
> result
This is what it's giving me:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[36,] 32 2 NA 32 2 NA "13580" "M" 2 NA
[37,] 32 3 124 32 3 124 "13580" "M" 3 124
[38,] 32 4 116 32 4 116 "13580" "M" 4 116
[39,] 33 2 410 33 2 410 "21525" "F" 2 410
[40,] 33 3 116 33 3 116 "21525" "F" 3 116