[R] Using diff and transform
David Winsemius
dwinsemius at comcast.net
Wed Jan 26 04:48:16 CET 2011
On Jan 25, 2011, at 9:58 PM, eric wrote:
>
> I want to use diff to take the differences in a column "Close" of a
> data
> frame "y". But I'd like to do it using the transform function so a
> new data
> frame is created with a difference column. The problem is that diff
> gives
> one less than the number of elements in the original data frame. So
> transform gives an error message. I know the first element of diff
> should be
> NA or ideally 0. But not sure how I get there. Any suggestions ?
>
>
> j
> Date Close
> 1 11/20/1985 156.412
> 2 11/21/1985 155.112
> 3 11/22/1985 154.182
> 4 11/25/1985 154.192
> 5 11/26/1985 153.722
> 6 11/27/1985 153.712
>
> d <-diff(j[,2])
> d
> [1] -1.30 -0.93 0.01 -0.47 -0.01
>
> j <- transform(j, delta=diff(j[,2]))
> j <- transform(j, delta=c(NA, diff(j[,2])))
> j
Date Close delta
1 11/20/1985 156.412 NA
2 11/21/1985 155.112 -1.30
3 11/22/1985 154.182 -0.93
4 11/25/1985 154.192 0.01
5 11/26/1985 153.722 -0.47
6 11/27/1985 153.712 -0.01
>
> Error in data.frame(list(Date = c(5620L, 5639L, 5657L, 5706L, 5721L,
> 5736L :
> arguments imply differing number of rows: 6, 5
> Calls: transform -> transform.data.frame -> do.call -> data.frame
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Using-diff-and-transform-tp3237397p3237397.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list