我想将一些编码为因子的行为与一个连续的协变量联系起来。潜在的动机是随着动物靠近协变量(与食物的距离),其行为将从搜索(行为1)变为喂养(行为2)。
因此,当动物处于行为1时,协变量应该大(到食物的距离较大),而在接近行为2时以及在这种状态下(到食物的距离短),协变量应该变小。一种皱纹是我有多只动物。
我的数据如下所示:
animalID behaviour
1 1
1 1
1 1
1 2
1 2
1 2
1 1
1 1
2 1
2 1
2 1
2 2
2 2
2 2
2 1
我想要这样的东西
animalID behaviour distance
1 1 100
1 1 99
1 1 98
1 2 58
1 2 57
1 2 60
1 1 74
1 1 75
2 1 104
2 1 101
2 1 100
2 2 40
2 2 44
2 2 42
2 1 86
答案 0 :(得分:1)
鉴于您没有任何协变量,因此没有太多的选择。做某事的最简单方法就是使用移动平均值并进行适当的变换
如果您确实有一些协变量要使用,并且想做一些更复杂的事情,则可以使用随机/蒙特卡洛方法。 Stan语言使您可以轻松地定义贝叶斯模型并从中进行采样。在这种情况下,您可以定义一个简单的自回归模型:
data {
int<lower=0> N; // number of data points
int<lower=0> animal[N];
real behaviour[N];
}
parameters {
real mu[N]; // the values you care about
real<lower=0> sigma_auto; // autocorrelation of values
real<lower=0> sigma_behaviour; // how close they should be to data
}
model {
for (i in 2:N) {
if (animal[i] == animal[i-1]) {
// autoregressive component of model
mu[i] ~ normal(mu[i-1], sigma_auto);
}
}
// comparison to data
behaviour ~ normal(mu, sigma_behaviour);
// priors
sigma_auto ~ cauchy(0, 0.05);
sigma_behaviour ~ cauchy(0, 0.05);
}
代码有点像R,但是我建议阅读manual。您可以通过以下方式运行它:
library(rstan)
df = read.table(text="animalID behaviour
1 1
...
", header=TRUE)
fit <- stan("model.stan", iter=1000, data=list(
N=nrow(df),
animal=df$animalID,
behaviour=df$behaviour
))
plot(df$behaviour)
mu <- extract(fit, 'mu')$mu
for (i in 1:nrow(mu)) {
lines(mu[i,], lwd=0.2)
}
stan
调用会编译模型(通过C ++编译器)并为iter
样本运行它。 extract
行将mu
的样本拉出后验,然后将其绘制在数据上。
希望有帮助!