[R] modify and append new rows to a data.frame using ddply

Santiago Guallar sguallar at yahoo.com
Mon Jun 10 11:49:18 CEST 2013


I have a data.frame that contains a variable act which records the duration (in seconds) of two states (wet-dry) for several individuals (identified by Ring) over a period of time. Since I want to work with daytime (i.e. from sunrise till sunset) and night time (i.e. from sunset till next sunrise), I have to split act from time[i] till sunset and from sunset until time[i+1], and from time[k] till sunrise and from sunrise until time[k+1].

Here is an example with time and act separated by a comma:

[i] 01-01-2000 20:55:00 , 360 
[i+1] 01-01-2000 21:01:00 , 30 # let's say that sunset is at 01-01-2000 21:00:00

[i+2] 01-01-2000 21:01:30 , 30

My goal is to get:
[i] 01-01-2000 20:55:00 , 300 # act is modified

[i+1] 01-01-2000 21:00:00 , 60 # new row with time=sunset

[i+2] 01-01-2000 21:01:00 , 30 # previously row i+1th

[i+3] 01-01-2000 21:01:30 , 30 # previously row i+2th

I attach a dput with a selection of my data.frame. Here is a piece of existing code that I am trying to adapt just for the daytime/night time change:


  xandaynight <- ddply( xan, .(Ring), function(df1){
  # index of day/night changes
  ind <- c( FALSE, diff(df$dif) == 1 )
  add <- df1[ind,]
  add$timepos <- add$dusk
  # rearrangement
  df1 <- rbind( df1, add )
  df1 <- df1[order(df1$timepos),]
  # recalculation of act
  df1$act2 <- c( diff( as.numeric(df1$timepos) ), NA )
  df1} )

This code produces an error message:
"Error en diff(df$dif): error in evaluating the argument 'x' in selecting a method for function 'diff': Error en df$dif: object of type 'closure' is not a subset"

Thank you for your help,


More information about the R-help mailing list