Ff Yy
Ff Yy

Reputation: 247

Strange thing happening: longer object length is not a multiple of shorter object length

x1 = c(1,2,3,4,5,6,7)
x1
[1] 1 2 3 4 5 6 7
x1[which(x1== c(5,6))]
[1] 5 6
Warning message:
In x1 == c(5, 6) :
longer object length is not a multiple of shorter object length

When I exit R and then reopen R I get this:

x1 = c(1,2,3,4,5,6,7)   
x1
[1] 1 2 3 4 5 6 7
x1[which(x1== c(5,6))]
[1] 5 6

The warnings message disappears. Why?

Upvotes: 0

Views: 1262

Answers (1)

Dason
Dason

Reputation: 62003

There are a few things to note here:

You should be getting that message because for exactly the reason that it says - the longer item's length isn't a multiple of the shorter item's length. This implies that what you think you're doing probably isn't what you're actually doing. You should receive this message every time you try to run that code - I don't know why you wouldn't have received the message one time you ran it.

You can index a vector using logical values so using which is unnecessary here.

What you're most likely looking for in the %in% operator. What you're currently doing is element by element comparison of equality and the shorter vector will 'recycle' itself until it's the same length as the longer vector. For example:

x1 <- c(1, 2)
x2 <- c(1, 2, 3, 4)
x1 == x2
#[1]  TRUE  TRUE FALSE FALSE

What this is doing is testing x1[1] against x2[1], then x1[2] against x2[2], then since there are no more elements in x1 it recycles back to the beginning and tests x1[1] against x2[3], then x1[2] against x2[4].

If instead we just wanted to find which elements of x1 are in the vector x2 then as mentioned previously the %in% operator takes care of that for us:

x1 %in% x2
#[1] TRUE TRUE

This is asking is x1[1] an element of x2? Is x1[2] an element of x2? So on and so forth...

Upvotes: 2

Related Questions