1
votes

I'm running into an issue that I feel should be simple but cannot figure out and have searched the board for comparable problems/question but unable to find an answer.

In short, I have data from a variety of motor vehicles and looking to know the average speed of the vehicle when it is at maximal acceleration. I also want the opposite - the average acceleration at top speed.

I am able to do this for the whole dataset using the following code

data<-data %>% group_by(Name) %>%
  mutate(speedATaccel= with(data, avg.Speed[which.max(top.Accel)]),
         accelATspeed= with(data, avg.Accel[which.max(top.Speed)]))

However, the group_by function doesn't appear to be working it just provide the values across the whole dataset as opposed to each individual vehicle group.

Any help would be appreciated.

Thanks,

1
Please make a reproducible example.Martin Gal

1 Answers

0
votes

The use of with(data, disrupt the group_by attribute and get the index on the whole data. Instead, use tidyverse methods, i.e. remove the with(data. Note that in tidyverse, we don't need to use any of the base R extraction methods i.e. with $ or [[ or with, instead specify the unquoted column name

library(dplyr)
data %>% 
      group_by(Name) %>%
      mutate(speedATaccel = avg.Speed[which.max(top.Accel)],
              accelAtspeed = avg.Accel[which.max(top.Speed)])