subtracting reaction time lefthand from reaction time righthand

I`m a beginner R coder and Psychology Student, and looking for your help :)

My problem is probably best described as followed:

I did an experiment. Every participant reacted either with the right or left hand. What I wanna do is

  1. Compute the mean reaction time per participant and used hand

  2. Per participant: MeanReactionTimeLeftHand minus MeanReactionTimeRightHand. I have several responses per participant and put them all together using r.bind. My df looks something like this (numbers all random)

    row participant RT usedHand
    [1] 1 0.4 right
    [2] 1 0.5 right
    [3] 1 0.3 left
    [4] 1 0.6 left
    [1] 2 0.3 right
    [2] 2 0.2 right
    [3] 2 0.1 left
    [4] 2 0.9 left

I computed the mean reaction time per participant and hand using

Df %>% group_by(participant) %>% group_by(hand, .add = TRUE) %>% 
mutate(mRTperParticipantAndHand = mean(RT)) %>% ungroup()

As you can see I put it behind every legible row.

The df locked like this:

|row|participant|   RT  |usedHand|mRTperParticipantAndHand|
|---|-----------|-------|--------|------------------------|
|[1]|1          |   0.4 |   right|  mRT1right             |
|[2]|1          |   0.5 |   right|  mRT1right             |
|[3]|1          |   0.3 |   left |  mRT1left              |
|[4]|1          |   0.6 |   left |  mRT1left              |
|[1]|2          |   0.3 |   right|  mRT2right             | 
|[2]|2          |   0.2 |   right|  mRT2right             |
|[3]|2          |   0.1 |   left |  mRT2left              |
|[4]|2          |   0.9 |   left |  mRT2left              |
    

I do have major problems with the second step. Either I want another column with MeanReactionTimeLeftHand minus MeanReactionTimeRightHand (with the same value for every participant) Or a new df with the column participant and MeanReactionTimeLeftHand minus MeanReactionTimeRightHand.
In my real df I have hundreds of RTs and several participants. So I`m looking for an automatic soloution. I tried different approaches but none of them worked.
Looking forward to your help!


We could first group by participant and hand, then calculate the mean, then pivot the data and substract as desired:

library(dplyr)
library(tidyr)  
df %>% 
  group_by(rowparticipant, usedHand) %>% 
  summarise(meanRT = mean(RT)) %>% 
  pivot_wider(
    names_from = usedHand,
    values_from = meanRT,
    names_prefix = "mean_"
  ) %>% 
  mutate(diff = round(mean_left - mean_right, 2))
  rowparticipant mean_left mean_right  diff
           <int>     <dbl>      <dbl> <dbl>
1              1      0.45       0.45  0   
2              2      0.5        0.25  0.25