【问题标题】:In [R], gen new variable for each value of group在 [R] 中,为组的每个值生成新变量
【发布时间】:2013-06-14 12:32:25
【问题描述】:

我有 id 变量和 date 变量,其中给定 id(面板)有多个日期。我想根据给定 id 的任何年份是否满足逻辑条件来生成一个新变量。我不确定如何对其进行编码,因此请不要将以下内容视为 R 代码,就像逻辑伪代码一样。类似的东西

foreach(i in min(id):max(id)) {
if(var1[yearvar[1:max(yearvar)]=="A") then { newvar==1}
}

举个例子:

ID     Year     Letter
1     1999        A
1     2000        B
2     2000        C
3     1999        A

应该返回newvar 1 1 0 1

由于data[ID==1]在某年包含A,它也应该在2000年包含==1,尽管那一年有Letter==B

【问题讨论】:

    标签: r syntax grouping time-series


    【解决方案1】:

    这是一种使用基础 R 接近它的方法:

    #Find which ID meet first criteria
    withA <- unique(dat$ID[dat$Letter == "A"])
    
    #add new column based on whether ID is in withA
    dat$newvar <- as.numeric(dat$ID %in% withA)
    
    #    ID Year Letter newvar
    # 1  1 1999      A      1
    # 2  1 2000      B      1
    # 3  2 2000      C      0
    # 4  3 1999      A      1
    

    【讨论】:

      【解决方案2】:

      这是使用plyr的解决方案:

      library(plyr)
      a <- ddply(dat, .(ID), summarise, newvar = as.numeric(any(Letter == "A")))
      merge(ID, a, by="ID")
      

      【讨论】:

      • 如果在ddply()中用transform替换summary,那么就不需要使用merge()。
      【解决方案3】:

      不使用包:

      dat <- data.frame(
          ID = c(1,1,2,3),
          Year = c(1999,2000,2000,1999),
          Letter = c("A","B","C","A")
      )
      tableData <- table(dat[,c("ID","Letter")])
      newvar <- ifelse(tableData[dat$ID,"A"]==1,1,0)
      dat <- cbind(dat,newvar)
      
      #  ID Year Letter newvar
      #1  1 1999      A      1
      #2  1 2000      B      1
      #3  2 2000      C      0
      #4  3 1999      A      1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-26
        • 2018-03-14
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 2011-03-23
        相关资源
        最近更新 更多