1

I am creating a new column. I want it to be based on two other columns that both hold logicals - Acct and Con. The result column should be the "OR" between them, so I tried:

lead.data$AcctOrCon <- lead.data$Acct || lead.data$Con

This made all the columns TRUE. I am assuming it's because it's checking if either column has TRUE at all in the whole column. I guess that makes sense.

So, I wrote this loop:

for(row in 1:nrow(lead.data))
{
   lead.data$AcctOrCon[row] <- lead.data$Acct[row] || lead.data$Con[row] 
}

This works fine, but I know there has to be a better way. Also, I've read that R isn't very fond of loops - this one's only about 50,000 lines, but I don't want to get bad habits when I'm dealing with a million. I've searched around and it seems like the first answer SHOULD work...

jeffsdata
  • 431
  • 4
  • 15
  • Can you provide a really short example of your data frame and your expected result? Pick out 5 rows from your data that you know have different values in lead.data$Acct and lead.data$Con and use dput() to paste them in your question. That will make it easier for someone to help you. Giving an expected result for each row will let us know what you're looking for - right now it's not completely clear. – Nova Mar 31 '16 at 15:32
  • 1
    Instead of `||` use just `|` as your "or" operator. From the help: "& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector." – zelite Mar 31 '16 at 15:33
  • The single pipe worked! I didn't even realize the difference. Thanks for your help and for the post about it. I've marked this as a duplicate and it now directs you to the single vs. double logical operators. =) – jeffsdata Mar 31 '16 at 15:59

0 Answers0