How to apply multiple functions per row in a dataframe in r then aggregate all results

Viewed 19

I have a data frame with 22k rows. I made multiple functions that can only run a specific row (which is named as sample) from the original data frame, then it will produce another data frame with 10 rows (which is named as part2). So if I tried running the functions in the whole data frame with 22k rows, it won't work. Code is like this:

sample <- DF[112,]

part2 <- data.frame(matrix(ncol = 9, nrow = 10))  

names(part2) <- c("IO", "Ben_Period", "Indicator_Ben_Period", "Yr", "Beg", 
              "End", "Sched_Annual_Payout", "Paid", "Unpaid")

for(i in 1) {
    part2$IO <- sample$Insurance_Object
    part2$Ben_Period[i] <- i
    part2$Indicator_Ben_Period[i] <- ifelse( part2$Ben_Period[i] <= sample$Plan_Type, 1, 0)
    part2$Yr[i] <-  as.numeric( format (sample$Maturity_Date, "%Y") )
    part2$Beg[i] <- sample$Total_Check_Amount
    part2$Sched_Annual_Payout[i] <- ifelse( part2$Indicator_Ben_Period[i] == 1, 
                                      sample$Annual_Allowance, 0)
    part2$End[i] <- part2$Beg[i] - part2$Sched_Annual_Payout[i]
    part2$Paid[i] <- ifelse( ifelse( part2$End[i] > 0, part2$Sched_Annual_Payout[i], 
                  part2$Beg[i] ) > 0, ifelse( part2$End[i] > 0, 
    part2$Sched_Annual_Payout[i],
                                              part2$Beg[i] ), 0)
    part2$Unpaid[i] <- part2$Sched_Annual_Payout[i] - part2$Paid[i]
}

for(i in 2:10) {
    part2$IO <- sample$Insurance_Object
    part2$Ben_Period[i] <- i
    part2$Indicator_Ben_Period[i] <- ifelse( part2$Ben_Period[i] <= sample$Plan_Type, 1, 0)
    part2$Yr[i] <-  part2$Yr[i-1] + 1
    part2$Beg[i] <- ifelse( part2$Indicator_Ben_Period[i] == 1, part2$End[i-1], 0)
    part2$Sched_Annual_Payout[i] <- ifelse( part2$Indicator_Ben_Period[i] == 1, 
                                      sample$Annual_Allowance, 0)
    part2$End[i] <- part2$Beg[i] - part2$Sched_Annual_Payout[i]
    part2$Paid[i] <- ifelse( ifelse( part2$End[i] > 0, part2$Sched_Annual_Payout[i], 
                               part2$Beg[i] ) > 0, ifelse( part2$End[i] > 0, 
                               part2$Sched_Annual_Payout[i], part2$Beg[i] ), 0)
    part2$Unpaid[i] <- part2$Sched_Annual_Payout[i] - part2$Paid[i]

}

I want to run every row in the DF with the function above and aggregate the results. Which will lead me to data frame named part2 but with the aggregated results of all columns in the DF with 22k rows.

0 Answers
Related