【问题标题】:spreading a binary variable by a grouping variable r通过分组变量 r 扩展二进制变量
【发布时间】:2018-07-18 07:48:30
【问题描述】:

我有一个数据集 (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 都相同,我希望这些变量在新数据库中成为单列,并且只为 Outcome 变量提供多列,如下所示:

   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 和 reshape,但我似乎无法将数据库转换为这种格式。例如当我使用代码时:

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

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

谢谢。

【问题讨论】:

标签: r reshape reshape2


【解决方案1】:

可以通过以下步骤使用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】:

    dcast 函数用于这样的事情。

    dcast(data, ID + DOB + Age ~ Outcome)
    

    【讨论】:

    • 谢谢。效果很好。如果我想传播多个结果变量会怎样?
    • 您将在等式的右侧添加另一个值。所以:dcast(data, ID + DOB + Age ~ Outcome + var2)
    • 这不起作用,它传播了 Outcome 和 var2 的值,以便我得到与两个变量的交叉表相对应的值。所以,假设我对 Outcome 的值是 1 和 0,而我对 var2 的值是“是”和“否”。我在结果数据集“1yes”、“0yes”、“1no”、“0no”中得到以下列名。我想将每个值分开。类似“1”、“0”、“是”、“否”。
    【解决方案3】:

    您可以使用tidyrdplyr

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

    【讨论】:

      猜你喜欢
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多