【问题标题】:Creating a vector with multiple sequences based on number of IDs' repetitions根据 ID 的重复次数创建具有多个序列的向量
【发布时间】:2013-11-16 00:32:41
【问题描述】:

我有一个带有面板数据的数据框,这些数据是受试者在一段时间内的特征。我需要创建一个列,其序列从 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))

【问题讨论】:

  • 如果中间有 qtty ==0 你想要 1,2,NA,4,5 或 1,2,NA,3,4 怎么办? (我假设 qtty==0 是 5-uplet subjet 序列的第三个值)
  • 好问题。那么在我的情况下,如果 qtty 列中的任何 0 总是在每个主题的最后一年。

标签: r aggregate sequences panel-data


【解决方案1】:

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

您要么沿着 subjet 生成一个序列,然后在 qtty 为零的地方用 NA 替换

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
})

【讨论】:

    【解决方案2】:

    已编辑

    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)
    

    这将提供你需要的东西

    【讨论】:

      猜你喜欢
      • 2019-12-26
      • 2018-10-31
      • 2019-09-13
      • 2013-08-31
      • 2018-07-28
      • 2017-06-28
      • 2018-09-14
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多