'For loop through columns of dataframe to create columns using ifelse statment : R version 4.1.2

Here is my issue: My dataframe has multiple events (events1 to events4, below) where the end of follow-up is time to ANY event. I converted this dataframe from wide to long format using survSplit. survSplit seems to only handle one event type at a time so I have decided to do it manually using a nested ifelse statement which seems to work until I want do the same operation in a for loop that will go from event column to event column (my real dataset has 33 outcome types). The loop fails and gives the following error message:

Error: Assigned data value must be compatible with existing data. x Existing data has 12 rows. x Assigned data has 0 rows. i Only vectors of size 1 are recycled. Run rlang::last_error() to see where the error occurred. In addition: Warning message: Unknown or uninitialised column: event.

 install.packages("survival")
 install.packages("dplyr")
 library(survival)
 library(dplyr)
 cutpoints.l <- c(1.25)
 f12 <- data.frame(id = 1:6,
              next.ivl= c(22.348, 1.837, 2.051,1.782,1.692, 1.730),
              event1 = c(0,1,0,0,1,0),
              event2 = c(1,0,0,0,0,1),
              event3 = c(0,0,1,1,0,0),
              event4 = c(0,0,0,0,0,0),
              enter= rep(0,6),
              end=c(22.348, 1.837,2.051,1.782,1.629,1.730))

 f12.split <- survSplit(Surv(next.ivl,event1)~.,f12, 
                   cut = cutpoints.l,
                   event = "event1",
                   start = "enter", 
                   end = "next.ivl",
                   episode = "ivl")

 f12.split <- f12.split %>%
   group_by(id) %>%
   mutate(n = ifelse(row_number() == 1, 1, 0))%>%
   mutate(N = ifelse(row_number() == n(), 1, 0))

 events<-grep("event", colnames(f12.split), value = TRUE)

 for (event in events) {
   print(event)
   f12.split$event<-ifelse(f12.split$N==1 & f12.split$event==1, ifelse(f12.split$n==1 & 
   f12.split$event==1,0,1),0)
   }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source