[R] Calculating column differences

William Michels wjm1 @end|ng |rom c@@@co|umb|@@edu
Wed Mar 24 18:59:28 CET 2021


Dear Jeff,

Rather than diff-ing a linear vector you're trying to diff values from
two different rows. Also you indicate that you want to place the
diff-ed value in the 'lower' row of a new column. Try this (note
insertion of an initial "zero" row):

> df <- data.frame(ID=1:5,Score=4*2:6)
> df1 <- rbind(c(0,0), df)
> cbind(df1, "diff"=c(0, diff(df1$Score)) )
  ID Score diff
1  0     0    0
2  1     8    8
3  2    12    4
4  3    16    4
5  4    20    4
6  5    24    4
>

HTH, Bill.

W. Michels, Ph.D.



On Wed, Mar 24, 2021 at 9:49 AM Jeff Reichman <reichmanj using sbcglobal.net> wrote:
>
> r-help forum
>
>
>
> I'm trying to calculate the diff between two rows and them mutate the
> difference into a new column. I'm using the diff function but not giving me
> what I want.
>
>
>
> df <- data.frame(ID=1:5,Score=4*2:6)
>
>
>
> What a want  where
>
>   ID Score  diff
>
> 1  1     8      8
>
> 2  2    12     4
>
> 3  3    16     4
>
> 4  4    20     4
>
> 5  5    24     4
>
>
>
> What I am getting
>
>   ID Score  diff
>
> 1  1     8      NA
>
> 2  2    12     4
>
> 3  3    16     4
>
> 4  4    20     4
>
> 5  5    24     4
>
>
>
> Jeff
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list