[R] diff in a dataframe
Don MacQueen
macq at llnl.gov
Thu Jan 10 16:58:25 CET 2008
So, what's the easiest way to add a column to a dataframe? Just do it.
Here is a really simple example to illustrate:
> foo <- data.frame(x=1:4,y=2:5)
> foo
x y
1 1 2
2 2 3
3 3 4
4 4 5
> foo$z <- c(NA,diff(foo$x))
> foo
x y z
1 1 2 NA
2 2 3 1
3 3 4 1
4 4 5 1
Solutions using apply and sapply are overly complicated for what you requested.
If you had to do this for many, many columns a looping solution would
be worth it, but for just two columns, it's not.
-Don
At 12:46 PM +0530 1/10/08, Vishal Belsare wrote:
>I have a dataframe say:
>
>date price_g price_s
> 0.34 0.56
> 0.36 0.76
> . .
> . .
> . .
>
>and so on. say, 1000 rows.
>
>Is it possible to add two columns to this dataframe, by computing say
>diff(log(price_g) and diff(log(price_s)) ?
>
>The elements in the first row of these columns cannot be computed, but
>can I coerce this to happen and assign a missing value there? It would
>be really great if I could do that, because in this case I don't have
>to re-index my transformed series to the dates again in a new
>dataframe.
>
>Thanks in anticipation.
>
>
>Vishal Belsare
>
>______________________________________________
>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.
--
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062
More information about the R-help
mailing list