代码之家  ›  专栏  ›  技术社区  ›  user183974

通过分组变量r扩展二进制变量

  •  1
  • user183974  · 技术社区  · 7 年前

    我有一个数据集(DF),看起来像下面的数据集:

       ID DOB      Age Outcome    
       1  1/01/80  18     1
       1  1/01/80  18     0
       2  1/02/81  17     1
       2  1/02/81  17     0
       3  1/03/70  28     1
    

    我想将我的数据库更改为宽格式,以便每个ID有一行。然而,鉴于每个ID的DOB和Age都相同,我希望这些变量在新数据库中是一列,并且只需为结果变量设置多个列,如下所示:

       ID DOB      Age Outcome.1 Outcome.2    
       1  1/01/80  18     1         0
       2  1/02/81  17     1         0
       3  1/03/70  28     1         NA
    

    我尝试过使用tidyr和reforme,但我似乎无法将数据库转换成这种格式。例如,当我使用代码时:

    spread(DF, key=ID, value = Outcome)
    

    我得到一个错误,表明我有重复的行标识符。有没有办法把数据库转换成我想要的格式?

    谢谢

    3 回复  |  直到 7 年前
        1
  •  2
  •   MKR    7 年前

    一种解决方案可以通过以下步骤实现: tidyverse . 我们的想法是 row number 到列,为每行提供唯一的ID。之后有不同的应用方法 spread .

    df <- read.table(text = "ID DOB      Age Outcome    
    1  1/01/80  18     1
    1  1/01/80  18     0
    2  1/02/81  17     1
    2  1/02/81  17     0
    3  1/03/70  28     1", header = T, stringsAsFactors = F)
    
    library(tidyverse)
    
    df %>% mutate(rownum = row_number(), Outcome = paste("Outcome",Outcome,sep=".")) %>%
      spread(Outcome, rownum) %>%
      mutate(Outcome.0 = ifelse(!is.na(Outcome.0),0, NA )) %>%
      mutate(Outcome.1 = ifelse(!is.na(Outcome.1),1, NA ))
    
    # Result:
    #  ID     DOB Age Outcome.0 Outcome.1
    #1  1 1/01/80  18         0         1
    #2  2 1/02/81  17         0         1
    #3  3 1/03/70  28        NA         1
    
        2
  •  1
  •   C-x C-c    7 年前

    dcast函数用于这样的事情。

    dcast(data, ID + DOB + Age ~ Outcome)
    
        3
  •  1
  •   Martin C. Arnold    7 年前

    你可以使用 tidyr dplyr :

       DF %>%
          group_by(ID) %>%
          mutate(OutcomeID = paste0('Outcome.', row_number())) %>%
          spread(OutcomeID, Outcome)