[R] Calculating difference in variable values (e.g. elapsed time) in data frame
Sarah Goslee
sarah.goslee at gmail.com
Thu Jul 28 18:02:53 CEST 2011
Hi,
On Thu, Jul 28, 2011 at 11:38 AM, Philippe Hensel
<Philippe.Hensel at noaa.gov> wrote:
> Hello,
>
> I have a data frame containing time (e.g. GMT), and I would like to
> create/add a new variable that would be the computation of the elapsed time
> since the first observation. Does anyone have a suggestion for an easy way
> to do this? I am having trouble creating a new variable that would contain
> just the first time observation (then I could take difference between actual
> time and initial time).
>
> e.g. - here's a brief representation of the data:
>
> time <-
> c("19:36:11","19:36:12","19:36:13","19:36:14","19:36:15","19:36:16")
> strptime(time, "%H:%M:%S")
> y<-c(197,194,189,179,166,150)
> mydata<-data.frame(time=time,y=y)
>
> OK, now how do I create a new variable, say, time_el, that would calculate
> the elapsed time since 19:36:11? I assume that I need the strptime()
> function to make sure R treats the character strings as time.
Thank you for providing a small reproducible example!
You missed one step, which is assigning the result of strptime() to a variable.
After that, you can just subtract.
time <- c("19:36:11","19:36:12","19:36:13","19:36:14","19:36:15","19:36:16")
time <- strptime(time, "%H:%M:%S")
y<-c(197,194,189,179,166,150)
timeel <- time - time[1]
mydata<-data.frame(time=time, y=y, timeel=timeel)
Sarah
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list