I have a data frame in which each column is a time series of numbers (from 0 to 8) representing different behaviors during animal courtship. I would like to check if there is a pattern such as a given behavior is followed more frequently by another one. I have written a function that allow me to do calculate the frequencies of behaviours that follow a given behavior after a particular time interval:
> data[,3]
[1] 1 1 1 1 7 7 3 3 7 3 1 1 8 1 3 3 3 5 1 1 4 ...
neighbor <- function(DATA, BEHAVIOR, INTERVAL)
{
total=c(0)
tmp = data.frame(total=c(0:8),Freq=rep(0,9))
number_of_x = which(DATA == BEHAVIOR)
for(i in number_of_x){
total = append(total,DATA[i+INTERVAL,])
}
tmp = merge(tmp,table(total), by=c("total"), all=T)
tmp[is.na(tmp)] <- 0
subset(tmp, select = ncol(tmp))
}
So I run the function for say the third column, behavior 3, and next behavior in time (1) and I get what I want:
> neighbor(as.data.frame(data[,3], 3, 1]
Freq.y
0 0.01
1 0.71
2 0.01
3 0.21
4 0.01
5 0.04
6 0.01
7 0.02
8 0.00
Now I would like to use a similar function to obtain the frequencies for the nine behaviours. Something like:
neighborAll <- function(DATA, INTERVAL)
{
total=c(0)
tmp = data.frame(total=c(0:8),Freq=rep(0,9))
for(a in c(0:8)){
number_of_x = which(DATA == a)
for(i in number_of_x){
total = c(total,DATA[i+INTERVAL,])
}
tmp=merge(tmp, table(total), by = c("total"), all=T)
tmp[is.na(tmp)] <- 0
}
tmp[,3:9]
}
> neighborAll(as.data.frame(data[,3], 1)
I get:
Error in merge.data.frame(tmp, table(total), by = c("total"), all = T) :
there is already a column named ‘Freq.x’
Any ideas would be welcomed. Thanks in advance, Jose