0

I don't understand this error:

Warning message:
In if ((t$carried2 == t$Dead5) & (t$carried2 == t$Dead6)) { :
  the condition has length > 1 and only the first element will be used

my piece of code:

if ((t$carried2 == t$Dead5) & (t$carried2 == t$Dead6)) {(t$Dead5 = 0) & (t$Dead6 = 0)}

This is probably crappy, but I am new. Anyways, I want to say if (this and that happen) {then this and that = 0

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
Chad
  • 149
  • 4
  • 11
  • What are you trying to get as a result? `if` is probably not the best choice. – Matthew Lundberg Jan 23 '14 at 04:04
  • 1
    A place to start is to read `?Logic` carefully on the differences between `&` and `&&`. – joran Jan 23 '14 at 04:07
  • I have a large data set and I have data in some columns that are counted twice and want to clean it up, what would you recommend if I have two conditions an when these conditions are meet then this must happen? – Chad Jan 23 '14 at 04:08
  • -1 for not searching. This has been asked/answered several times. – Joshua Ulrich Jan 23 '14 at 14:54
  • @ Joshua, I actually did alot of searching, since last Friday and this never appeared in my search engine. I would be glad to show you. – Chad Jan 23 '14 at 14:58
  • I don't know what search terms you used, but searching for the exact warning/error usually results in several hits. For example: ["the condition has length > 1 and only the first element will be used"](http://stackoverflow.com/search?q=%5Br%5D+%22the+condition+has+length+%3E+1+and+only+the+first+element+will+be+used%22). – Joshua Ulrich Jan 23 '14 at 15:10

2 Answers2

2

How about this:

indices <- (t$carried2 == t$Dead5) & (t$carried2 == t$Dead6)

t$Dead5[indices] <- 0
t$Dead6[indices] <- 0

This sets the the values of t$Dead5 and t$Dead6 to zero, in those rows where the condition is TRUE.

You say in your comment that you want to clean up the data frame. Here is how you remove the rows for which indices is TRUE. With indices as above:

t <- t[!indices,]
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
2

The if clause in R expects a single boolean value: TRUE or FALSE.

By using & you're returning a vector of booleans, that's the cause of warning:

...only the first element will be used

So it will pick the first boolean and use it to test the if-else.

You may want to look at ifelse which works like a 'vectorized' if-else operator. Also look at the differences between & and &&:

& 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. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.

Fernando
  • 7,785
  • 6
  • 49
  • 81