Delia, name <- data.frame(Behavior=c(1, 2, 1, 2, 1), Time=c(0, 40, 45, 55, 57))
appear <- name$Time[name$Behavior==1] disappear <- name$Time[name$Behavior==2] if(length(appear) > length(disappear)) disappear <- c(disappear, 60) sum(disappear - appear) Delia Shelton wrote on 04/09/2012 12:30:23 PM: > Hi, > > I am attempting to tabulate binned data. The '1' represents the > appearance of the focal mouse pup, and '2' represents the > disappearance of the focal mouse pup. The code written below is > intended to calculate the total time spent appeared out of 3600s. > For Sample 1, both the hand calculation and R code yield the same > result, 50. A problem seems to occur when '1' is the last entry. For > Sample 2, the total time appeared is 53 (hand calculation), > however, using the R code below yields 55. If you have any > suggestions for solving the problem, please let me know. > > Thank you in advance for any assistance you may provide. > > Delia > > > Sample 1 > > 0.0 1 > 40 2 > 45 1 > 55 2 > > > Sample 2 > > 0.0 1 > 40 2 > 45 1 > 55 2 > 57 1 > > > > name = read.table(file.choose(),header=F) # opening a data file > colnames(name)<-c("Time", "Behavior") > name = data.frame(name$Behavior, name$Time) > colnames(name)<-c("Behavior", "Time") > name<-name[name$Time < 3600, ]; > > ## run file > > x<-seq(0,3600, by = 60) # total time partition by time which is 60 > > if (tail(name$Behavior, 1) == 1) {name<-rbind(name, c(4, 3600))} else > {name<-rbind(name, c(1, 3600))} > > if (nrow(name) %% 2 != 0) > {name <-name[-c(nrow(name)), -c(nrow(name))]} > > q<-NULL > for (y in (1: nrow(name))) > { > if (y %% 2 != 0) > q<-c(q, (c(name$Time[y]:name$Time[y +1]))) > } > > b<-table(cut(q,x)) > > sum(b) [[alternative HTML version deleted]] ______________________________________________ R-help@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.