Skip to content
Prev 269044 / 398502 Next

Coding question for behavioral data analysis

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hello,

as far as I understood your problem, this function might do the trick:

CountNextBehavior <- function (data.source, interest.behavior,
			       lev.ignore, interest.timeframe) {
  ## ------------------------------
  ## Returns the number of occuring behavior in a given timeframe
  ##
  ## Args:
  ##   data.source is the source dataframe, with columns Behavior and
  ##    Time. Behavior is assumed to be a factor and Time an integer
  ##   interest.behavior is the seeked level of the behavior
  ##   lev.ignore is a vector of behavior levels to ignore
  ##   interest.timeframe fixes the time frame for observation count
  ##
  ## Returns:
  ##   a matrix named according to the behaviors

  # First, get rid of unwanted behavioral levels
  data.source <- with(data.source[!data.source$Behavior %in%
				   lev.ignore, ],
		      data.frame(Time = Time,
				 Behavior = factor(Behavior)))
  # Creates the return matrix
  seeked.blevels <- levels(data.source$Behavior)
  count.behavior <- matrix(rep(0,length(seeked.blevels)), nrow=1,
			   dimnames=list("Count", seeked.blevels))
  # Look when the behavior occurs
  seeked.behavior <- data.source$Behavior == interest.behavior
  occuring.time <- data.source$Time[seeked.behavior]

  # Iterate over occuring times
  for (obs.time in occuring.time) {
    # Get all the observed behavior in the given timeframe
    this.timeframe <- data.source$Time > obs.time &
		      data.source$Time <= obs.time + interest.timeframe
    this.behavior <- data.source$Behavior[this.timeframe]
    # Get the level of the first observed behavior
    first.behavior <- this.behavior[1]
    # Count the number of occurences
    this.count <- sum(this.behavior == first.behavior)
    # Add the count to the given behavior
    count.behavior[first.behavior] <- count.behavior[first.behavior] +
				      this.count
    }

  return(count.behavior)
}

Am 18.08.2011 19:29, schrieb jabroesch:
- -- 
- --
RD
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJOThLwAAoJEPy6W3H9JxwxdiUH+gItFSU2shX/82vbZdffIs6l
NyGgNP6FSQBSI8zJB+jZQG/+g6s18Lf7E1idcvcY9lbaU8jwsL5cj7eeyV3mTKgq
HQbDthNkvrrMofQwFbTo5m0DesRMHPzNa9H9SChxXH8hYTxX1eEzEBAtDRsEeBL6
Tx4FbYH6FLBSr7IZ2dlNlw/9QbbLVg1a1w5IkKvyDQUwKPqCtIoCnKX55JYC0CYR
S3TeaxC1jJw6mMdJkO2xNsXxKvsU5zS+HC6AeK6GdKzXw76rQucUJExea2Z+tAtc
uPBc9gtObP4/BsRnmv5NikCVaZNZzJg8TZZbnh2/Siw1isUSPPtm46P38EUhx94=
=ruSU
-----END PGP SIGNATURE-----