0

I am trying to write back the results within a for loop to a new dataframe that i created. i would like to iterate through each row and then write the results to the last row on the data frame (lastrow + 1). Unfortunately, I am stuck and can't get the results to write-back.

#create a new dataframe
results<- data.frame(Fields=character(), Employee=character(), Plan=character())

a<-COMP30$PFRPrint_Has_Plan
b<-COMP30$PFRPrint_Is_Eligible
c<-COMP30$`Employee ID`
d<-results$Employee

matches<-cbind(a,b,c)
res<-cbind(d)
for (k in 1:nrow(matches)){
  if (matches[k,1]==TRUE & matches[k,2]==FALSE){
    results[nrow(results$Employee)+1,1]<-matches[k,3]   
  }
}
Chris2015
  • 1,030
  • 7
  • 28
  • 42
  • Please provide reproducible & minimal sample data along with your expected output. – Maurits Evers Feb 20 '20 at 21:42
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 20 '20 at 21:42
  • @conor - i would like perform loop for multiple scenarios and return the results, so I'm not sure the filter method would work or I don't know how to modify it to compound my results once I add additional if scenarios – Chris2015 Feb 21 '20 at 01:58

1 Answers1

0

If I've correctly understood what you're trying to do, you're trying to filter COMP30$`Employee ID` to just those cases where COMP30$PFRPrint_Has_Plan == TRUE and COMP30$PFRPrint_Is_Eligible == FALSE.

So why not simply go

library(dplyr)
results <- COMP30 %>%
  filter(PFRPrint_Has_Plan,
         !PFRPrint_Is_Eligible) %>%
  select("Employee ID") # Might need backticks for that column name

Since your loop doesn't specify values for the Fields or Plan columns, I assume you are adding them to results later

conor
  • 1,204
  • 1
  • 18
  • 22