Selecting rows based on pivot_wide binary table

Hi there! I am new to R and could really use help! I have this table below I created with a pivot function that is organized by unique patients then the columns are unique respiratory/cardio procedures each patient could have had. 1 = yes to that procedure. I want to group patients by if they have/have not received certain procedures (1. Non-invasive NI procedure, 2. Invasive intubation procedures, and 3. Neither NI or Intubations). I could use help with my code--it is not working for some reason! I have the table and my code below.

Proc <- read.csv("Procedure.csv", stringsAsFactors = F)

AllProc <- select(Proc, Case.Index.Id, Procedure.Name)
AllProcTidy <- pivot_wider(AllProc,
names_from = Procedure.Name,
values_from = Procedure.Name,
values_fill = 0,
values_fn = function(x) 1)

NI_RespPro <- c("BiPAP", "BiPAP (non-invasive)", "CPAP", "CPAP (Non-Invasive")
NI_tx <- filter(AllProcTidy, %in% NI_RespPro, group_by = Case.Index.Id)

Invasive_RespPro <- c("Endotracheal Intubation(and duration of intubation)")
Invasive_tx <- filter(AllProcTidy, %in% Invasive_RespPro)

No_tx <- filter(AllProcTidy, !Procedure.Name %in% c(NI_RespPro, Invasive_RespPro))

Hello @trangility,

If you can provide some dummy data / reprex we can have a proper look :slight_smile: FAQ: How to do a minimal reproducible example ( reprex ) for beginners

1 Like

stringsAsFactors = FALSE,
check.names = FALSE,
Case.Index.Id = c("0CF237EF-557E-40BC-8AB1-000016588E70",
BiPAP (non-invasive) = c(1,0,1,0,0,
CPAP (Non-Invasive) = c(0,0,1,0,0,
BiPAP = c(0,0,0,0,0,
Endotracheal Intubation(and duration of intubation) = c(0,0,0,0,0,

For filtering the wide table, you can use dplyr::filter_at to select several columns to filter from. To get all patients that received an NIV treatment you can do:


Within the vars() argument, you can specify a vector that contains the names of the columns to filter from, and with any_vars() you specify that your filtering conditions needs to match in one of the selected columns in order to retain the corresponding row.
For filtering patients that have not received any treatment, you can instead select all columns excpet the case ID: vars(-Case.Index.Id) and then filter so that all selected coloumns must have zero by using all_vars(.==0) instead of the any_vars() argument.

Just a little caveat if you have patitents that received both, NIV and invasive treatments will appear in both groups if you use this solution. Not sure if that will be a problem for you, but it's something to keep in mind.

I hope that this is a solution that will help you.

Thank you so much!! Worked!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.