0

I currently have an EMG data frame called all_ext that I need to extract data from. The data frame looks like this.

LHvector RHvector trigger time group
-1.279411e-01 0.1422139707 1 0.0000 L
-8.294112e-02 0.1112139707 1 0.0005 L
-3.794112e-02 0.0642139707 1 0.0010 L
-4.394112e-02 0.0422139707 1 0.0015 L
2.058879e-03 -0.014786029 1 0.2000 L
7.605888e-02 0.023213971 2 0.0000 L

and so on (I jumped a little to elaborate).

There are 2 groups (L, R), each with 50 triggers, that has a time from 0s to 0.2s.

What I want to do is to extract all 5 values (LHvector, RHvector, trigger, time, and group) when RHvector is at its max for all groups and triggers.

What I wrote so far is aggregatedval <- aggregate(x = all_ext$RHvector, by = list(all_ext$group, all_ext$triggers), max) which gave me the trigger and group value and group 1 and 2, and max RHvector as my x.

Group.1 Group.2 x
L 1 0.64821397
R 1 0.14332592
L 2 0.66621397
R 2 0.05932592
L 3 0.28721397
R 3 0.05832592

But I want the time and LHvector value when that RHvector is at max as well. I tried to do a follow-up search with

MaxRHTime <- all_ext$time[all_ext$RHvector == aggregatedval$x]

which resulted in an odd time value of 0.0250 0.0095 0.0310 0.0860

I am super stuck. I feel like I can edit the aggregate function max to be something more useful and specific to RHvector so I can return more than 1 value as well.

Please help.

  • Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Aug 18 '21 at 06:05
  • Using `dplyr` : `all_ext %>% group_by(trigger, group) %>%slice(which.max(RHvector))` – Ronak Shah Aug 18 '21 at 07:19
  • @RonakShak That works! Thank you! – Gap Sriutaisuk Aug 18 '21 at 22:40

1 Answers1

0

First make sure your data frame is sorted by your grouping variables and RHvector

all_ext=all_ext[order(all_ext$group,all_ext$trigger,all_ext$RHvector),]

then split by them and take the last row

do.call(rbind,by(all_ext,list(all_ext$group,all_ext$trigger),tail,1))
user2974951
  • 9,535
  • 1
  • 17
  • 24