【发布时间】:2017-09-26 23:14:14
【问题描述】:
我正在分析一个长期的动物标记重新捕获数据集,其中捕获的个体在每次捕获时被分配到 5 个大小类别中的 1 个。我需要创建一个矩阵,该矩阵在已知值(即观察动物的年数)之间和之外进行插值,并包括对个体可以在每个尺寸类别中停留多长时间的限制。
以下是跨越 20 年的五个样本捕获历史记录(CH;个人=行)(列)。有五种数字编码的可能尺寸等级(1=最小)。 NA 是动物未被捕获的年份(此处视为缺失值)。
第一次可以观察到任何体型等级的个体(例如第 1 行与第 3 行),我们可能会重新捕获跳过某个体型等级的个体(例如第 2 行)。
CH <- rbind(c(NA,NA,1,2,rep(NA,7),3,rep(NA,8)),
c(1,rep(NA,9),3,NA,NA,3,rep(NA,6)),
c(rep(NA,10),4,NA,NA,5,rep(NA,6)),
c(3,rep(NA,17),5,NA),
c(rep(NA,7),2,rep(NA,8),4,rep(NA,3)))
CH
> CH
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] NA NA 1 2 NA NA NA NA NA NA NA 3 NA NA NA NA NA NA NA NA
[2,] 1 NA NA NA NA NA NA NA NA NA 3 NA NA 3 NA NA NA NA NA NA
[3,] NA NA NA NA NA NA NA NA NA NA 4 NA NA 5 NA NA NA NA NA NA
[4,] 3 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 5 NA
[5,] NA NA NA NA NA NA NA 2 NA NA NA NA NA NA NA NA 4 NA NA NA
我已经弄清楚如何使用 imputeTS 包中的 na.interpolation() 函数在没有约束的情况下插入值,如下所示:
#ImputeTS missing values (with NO constraints, not ideal)
library(imputeTS)
ms.init.z <- function(ms, notseen){
state <- ms # capture history called state
for(i in 1:dim(state)[1]){ #Do this for every row/individual
if(any(!is.na(state[i,1:dim(state)[2]-1]))){ #If any are not NA through the 2nd to last occs'n
state[i,dim(state)[2]] <- max(state[i,],na.rm=TRUE) #Apply max state value for that individual to final year
#populate last column as as.interpolation needs at least two values
state[i,] <- ceiling(na.interpolation(state[i,])) # interpolate
} #if
m <- min(which(!is.na(ms[i,]))) #identify the first occasion not NA
state[i,1:(m-1)] <- NA #Replace before and on first occasion with NA
} #i
return(state)
} #function
CH.X <- ms.init.z(CH,NA)
> CH.X
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] NA NA 1 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
[2,] NA 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3
[3,] NA NA NA NA NA NA NA NA NA NA 4 5 5 5 5 5 5 5 5 5
[4,] NA 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5
[5,] NA NA NA NA NA NA NA 2 3 3 3 3 4 4 4 4 4 4 4 4
但是,我想限制每个人在每个尺寸级别中可以保留多少年。我正在努力寻找一个可以让我实现自定义约束的包。
我的“理想”输出如下所示。请注意,对于每一行的大多数(全部?)都有一个以上的解决方案,这很好,只要每个大小类别中的观察数量不超过最大值(如下所示)。
#Desired constraints (maximum # of years in each size)
#Size class 1= 1 year max; 2= 7 yrs max; 3= 7 yrs max;
#4= 15 yrs max; 5= no limit
#Example Desired output
CH.cor <- rbind(c(NA,NA,1,rep(2,5),rep(3,6),rep(4,6)),
c(1,rep(2,6),rep(3,7),rep(4,6)),
c(rep(4,12),rep(5,8)),
c(rep(3,3),rep(4,15),5,5),
c(rep(NA,6),1,rep(2,7),rep(3,6)))
CH.cor
> CH.cor
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] NA NA 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4
[2,] 1 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4
[3,] 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5
[4,] 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5
[5,] NA NA NA NA NA NA 1 2 2 2 2 2 2 2 3 3 3 3 3 3
任何建议或帮助将不胜感激。提前致谢。
【问题讨论】:
标签: r interpolation missing-data imputation imputets