1

I would like to return the result in a vector based on the results of an if statement. My default value in the column would be "blank" and if both conditions are met ==FALSE I would like the vector/cell to have "some text". Here is what I have so far:

COMP30$Test_3<-"blank"
matches<-list(c(COMP30$PMPI_Has_Plan,COMP30$PMPI_Is_Eligible,COMP30$Test_3))
for (match in matches){if (match[1]==FALSE & match[2]==FALSE){match[3]<-"some text"}}

After running, I am showing only "blank" even though there are instances of ==FALSE & ==FALSE. Basically, either the condition is not evaluating or the result is not being returned. Just started learning R so I am not sure what I am missing. Thanks!

2
  • You are modifying the variable match in the loop that is erased at each iteration. Modify matches instead Commented Feb 20, 2020 at 13:01
  • Thanks. What code needs to change in order to modify matches? Commented Feb 20, 2020 at 13:06

1 Answer 1

1

From what I can guess about your dataset. Please provide your data using dput.

Using vectorisation:

COMP30$Test_3<-"blank"
matches <- cbind(COMP30$PMPI_Has_Plan, COMP30$PMPI_Is_Eligible, COMP30$Test_3)
matches[!matches[,1] & !matches[,2],3] <- "Some text"

Or with a for loop:

matches <- cbind(COMP30$PMPI_Has_Plan, COMP30$PMPI_Is_Eligible, COMP30$Test_3)
for (k in 1:nrow(matches)){
  if (!matches[k, 1] & !matches[k, 2]){
    matches[k, 3] <- "some text"
  }
}
Sign up to request clarification or add additional context in comments.

13 Comments

I tried both solutions and I am still not returning the expected result or "some text". For example, I modified the vectorisation solution slightly to say: matches[matches[,1]==TRUE & matches[,2]==TRUE,3]<-"some text" but I only return "blank". I modified solution 2 similarly ==TRUE with the same result. Any ideas? Is it a syntax issue perhaps?
@Chris2015 Is your column boolean or string ? Using boolean == TRUE is equivalent to boolean as it is alread true or false
I see. It is boolean. But if I use ==FALSE for both I still don't return a result. Does it matter that the first two columns in cbind are boolean and the third column is string?
First two are logical and the third is character.
Code working : matches <- data.frame(a=c(T, F), b = c(T, T), c= "blank", stringsAsFactors = F);matches[matches[,1] & matches[,2],3] <- "Some text";matches. Edit your question and give us dput(head(matches))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.