Using Mutate in R to perform a calculation on a column

Hi, I'm starting to use dplyr and need some help.
I'm working on a dataset and need to manipulate the column DaH1
to create a new column DaH3.
DaH3 will be the result of deducting the second row value of
DaH1 from the first row value of DaH1 etc.
After this I should end up with a vector DaH3 with values:
4,3,5,6,6,10.

I cant see how to do this using mutate.
Also the final value in row 7 will be a problem.
I'd like to assign a 0 or NA to this if possible.
Could anyone please advise how I can proceed.

library(tidyverse)

originalData <- tibble(
                  DaH1=c(128, 124, 121, 116, 110, 104, 94),
                  DaH2=c(124, 117, 116, 112, 107, 101, 97),
                )

> racehorse_data
  DaH1 DaH2 
1  128  124  
2  124  117  
3  121  116  
4  116  112  
5  110  107  
6  104  101  
7  94   97  
suppressPackageStartupMessages(library(dplyr))
originalData <- tibble(
  DaH1=c(128, 124, 121, 116, 110, 104, 94),
  DaH2=c(124, 117, 116, 112, 107, 101, 97),
) -> racehorse_data 

racehorse_data %>% mutate(DaH3 = lag(DaH1,1) - DaH1)
#> # A tibble: 7 x 3
#>    DaH1  DaH2  DaH3
#>   <dbl> <dbl> <dbl>
#> 1   128   124    NA
#> 2   124   117     4
#> 3   121   116     3
#> 4   116   112     5
#> 5   110   107     6
#> 6   104   101     6
#> 7    94    97    10

Created on 2020-08-05 by the reprex package (v0.3.0)

Many Thanks for the help!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.