通过分组变量 r 扩展二进制变量
spreading a binary variable by a grouping variable r
我有一个数据集 (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)
我收到一条错误消息,表明我有重复的行标识符。有没有办法让数据库变成我想要的格式?
谢谢。
dcast 函数用于此类事情。
dcast(data, ID + DOB + Age ~ Outcome)
您可以使用 tidyr
和 dplyr
:
DF %>%
group_by(ID) %>%
mutate(OutcomeID = paste0('Outcome.', row_number())) %>%
spread(OutcomeID, Outcome)
一个解决方案可以通过以下步骤使用 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
我有一个数据集 (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)
我收到一条错误消息,表明我有重复的行标识符。有没有办法让数据库变成我想要的格式?
谢谢。
dcast 函数用于此类事情。
dcast(data, ID + DOB + Age ~ Outcome)
您可以使用 tidyr
和 dplyr
:
DF %>%
group_by(ID) %>%
mutate(OutcomeID = paste0('Outcome.', row_number())) %>%
spread(OutcomeID, Outcome)
一个解决方案可以通过以下步骤使用 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