根据ID重复次数创建具有多个序列的向量

时间:2013-11-05 07:32:24

标签: r aggregate sequences panel-data

我有一个数据框,其中包含面板数据,主题随时间变化。我需要创建一个列,其序列从1到每个主题的最大年份。例如,如果主题1在2000年到2005年的数据框中,我需要以下顺序:1,2,3,4,5,6。

以下是我数据的一小部分。最后一列(exp)就是我想要的。另外,如果你看一下第一个主题(13),你会发现在2008年,qtty的值为零。在这种情况下,我只需要NA或代码(01-9999),无论哪一个都无关紧要。

数据下面是我为获取该向量所做的工作,但它不起作用。

任何帮助将不胜感激。

subject season qtty exp
    13  2000    29  1
    13  2001    29  2
    13  2002    29  3
    13  2003    29  4
    13  2004    29  5
    13  2005    27  6
    13  2006    27  7
    13  2007    27  8
    13  2008    0   NA
    28  2000    18  1
    28  2001    18  2
    28  2002    18  3
    28  2003    18  4
    28  2004    18  5
    28  2005    18  6
    28  2006    18  7
    28  2007    18  8
    28  2008    18  9
    28  2009    20  10
    28  2010    20  11
    28  2011    20  12
    28  2012    20  13
    35  2000    21  1
    35  2001    21  2
    35  2002    21  3
    35  2003    21  4
    35  2004    21  5
    35  2005    21  6
    35  2006    21  7
    35  2007    21  8
    35  2008    21  9
    35  2009    14  10
    35  2010    11  11
    35  2011    11  12
    35  2012    10  13

我的代码:

numbY<-aggregate(season ~  subject, data = toCountY,length)
colnames(numbY)<-c("subject","inFish")
toCountY$inFish<-numbY$inFish[match(toCountY$subject,numbY$subject)]
numbYbyFisher<-unique(numbY)
seqY<-aggregate(numbYbyFisher$inFish, by=list(numbYbyFisher$subject), function(x)seq(1,x,1))

2 个答案:

答案 0 :(得分:2)

我正在使用ddply,我区分了两种情况:

您可以沿着子喷射生成序列,并使用NA替换,其中qtty为零

ddply(dat,.(subjet),transform,new.exp=ifelse(qtty==0,NA,seq_along(subjet)))

或者你生成一个qtty不同于零的序列,跳跃你qtty为零

ddply(dat,.(subjet),transform,new.exp={
  hh <- seq_along(which(qtty !=0))
  if(length(which(qtty ==0))>0) 
    hh <- append(hh,NA,which(qtty==0)-1)
  hh
})

答案 1 :(得分:0)

EDITED

ind=qtty!=0

exp=numeric(length(subject))
temp=0

for(i in 1:length(unique(subject[ind]))){
temp[i]=list(seq(from=1,to=table(subject[ind])[i]))
}

exp[ind]=unlist(temp)

这将提供您所需要的