[R] modify and append new rows in a dataframe

Santiago Guallar sguallar at yahoo.com
Sat Jun 8 11:19:06 CEST 2013

My data frame shows changes on the variable act which records the consecutive duration (in seconds) of two states (wet-dry) over a few days for several individuals (identified by Ring). Since I want to work with daytime (i.e. from dawn till dusk) and night time (i.e. from dusk till next dawn), I have to split act in two: from time[i] till dusk and from dusk until time[i+1], and from time[k] till dawn and from dawn until time[k+1].

ith row: 01-01-2000 20:55:00 act= 360 seconds

i+1th row: 01-01-2000 21:01:00 act= 30 seconds # say that dusk= 21:00

i+2th row: 01-01-2000 21:01:30 act= 30 seconds


My goal is to get:

ith row: 01-01-2000 20:55:00 act= 300 seconds # modified row

i+1th row: 01-01-2000 21:00:00 act= 60 seconds # new row

i+2th row: 01-01-2000 00:01:00 act= 30 seconds # previously row i+1th

i+3th row: 01-01-2000 00:01:30 act= 30 seconds # previously row i+2th


I attach a dput with a selection of my data. Here's a piece of code that I am trying to run only for the daytime/night time change:

  xandn <- ddply( xan, .(Ring), function(df1){
  # índex of daytime/night time changes
  ind <- c( FALSE, diff( as.POSIXlt( df1$timepos, df1$dusk ) ) > 0 )
  add <- df1[ind,]
  add$timepos <- add$timepos - add$dusk
  # append and arrange rows
  df1 <- rbind( df1, add )
  df1 <- df1[order(df1$timepos),]
  # recalculation of act
  df1$act2 <- c( diff( as.numeric(df1$timepos) ), NA )
  df1} )

I get the following error message:
"Error in diff(as.POSIXlt(df1$timepos, df1$dusk)): error in evaluating the argument 'x' in selecting a method for function 'diff': Error in as.POSIXlt.POSIXct (df1$timepos, df1$dusk):   invalid 'tz' value"

Thank you for your hep,


More information about the R-help mailing list