Создание двоичных категориальных переменных на основе содержимого списка с разделителями столбцов - PullRequest
1 голос
/ 07 апреля 2020

У меня есть переменная в моем фрейме данных, которая называется "Cardia c Типы коморбидности" с NA или списком различных типов комедии, разделенных столбцами. Как я могу сделать столбец для каждой возможной коморбидности, а затем заполнить наблюдения с 1/0, где 1 = указывает на наличие коморбидности и 0 = нет коморбидности.

dput(head(et1$`Cardiac Comorbidity Types`,20))
c("MI,", NA, "CAD, Previous CABG or PTCA, MI, Pacemaker,", "Arrhythmia,", 
"CAD, Previous CABG or PTCA, MI, Arrhythmia,", NA, "CAD, Previous CABG or PTCA, MI,", 
"CAD, Previous CABG or PTCA, CHF, Pacemaker,", "CAD, Previous CABG or PTCA,", 
"CAD, Previous CABG or PTCA, Arrhythmia,", "CAD, Previous CABG or PTCA,", 
"CAD, Previous CABG or PTCA, MI,", "CAD, Previous CABG or PTCA, CHF, Arrhythmia,", 
"CAD, Previous CABG or PTCA, Pacemaker,", "CAD, Previous CABG or PTCA, MI, CHF,", 
"CAD, Previous CABG or PTCA, MI, CHF,", NA, "CAD, Previous CABG or PTCA, PVD, Pacemaker,", 
"PVD,", "CAD, Previous CABG or PTCA,")

Кроме того, как я могу это сделать, если данные разделены точкой с запятой?

Ответы [ 2 ]

1 голос
/ 07 апреля 2020

Мы можем использовать cSplit_e из splitstackshape для преобразования в двоичные столбцы.

splitstackshape::cSplit_e(et1, "Cardiac.Comorbidity.Types", 
                          type = "character", fill = 0)

Аргумент по умолчанию sep в cSplit_e равен ",", если у вас есть данные, разделенные точкой с запятой, вы можете явно указать это.

splitstackshape::cSplit_e(et1, "Cardiac.Comorbidity.Types", sep = ";", 
                          type = "character", fill = 0)
1 голос
/ 07 апреля 2020

Мы можем использовать комбинацию unnest и pivot_wider из tidyr.

library(dplyr)
library(tidyr)
library(stringr)
data <- data %>% mutate(ID = 1:nrow(data))

data %>% 
  mutate(Cardiac.Comorbidity.Types = str_split(Cardiac.Comorbidity.Types, ", ?")) %>%
  unnest(Cardiac.Comorbidity.Types) %>%
  filter(Cardiac.Comorbidity.Types != "") %>%
  pivot_wider(id_cols = "ID", names_from = Cardiac.Comorbidity.Types, values_from = Cardiac.Comorbidity.Types) %>%
  right_join(data, by="ID") %>%
  mutate_at(vars(-ID,-Cardiac.Comorbidity.Types), ~ as.integer(!is.na(.x))) %>% select(-ID)
# A tibble: 20 x 8
#      MI   CAD `Previous CABG or PTCA` Pacemaker Arrhythmia   CHF   PVD Cardiac.Comorbidity.Types                   
#   <int> <int>                   <int>     <int>      <int> <int> <int> <fct>                                       
# 1     1     0                       0         0          0     0     0 MI,                                         
# 2     0     0                       0         0          0     0     0 NA                                          
# 3     1     1                       1         1          0     0     0 CAD, Previous CABG or PTCA, MI, Pacemaker,  
# 4     0     0                       0         0          1     0     0 Arrhythmia,                                 
# 5     1     1                       1         0          1     0     0 CAD, Previous CABG or PTCA, MI, Arrhythmia, 
...

Данные

data <- c("MI,", NA, "CAD, Previous CABG or PTCA, MI, Pacemaker,", "Arrhythmia,", 
"CAD, Previous CABG or PTCA, MI, Arrhythmia,", NA, "CAD, Previous CABG or PTCA, MI,", 
"CAD, Previous CABG or PTCA, CHF, Pacemaker,", "CAD, Previous CABG or PTCA,", 
"CAD, Previous CABG or PTCA, Arrhythmia,", "CAD, Previous CABG or PTCA,", 
"CAD, Previous CABG or PTCA, MI,", "CAD, Previous CABG or PTCA, CHF, Arrhythmia,", 
"CAD, Previous CABG or PTCA, Pacemaker,", "CAD, Previous CABG or PTCA, MI, CHF,", 
"CAD, Previous CABG or PTCA, MI, CHF,", NA, "CAD, Previous CABG or PTCA, PVD, Pacemaker,", 
"PVD,", "CAD, Previous CABG or PTCA,")
data <- data.frame(Cardiac.Comorbidity.Types = data)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...