Reputation: 3
I am working in R and have found a strange behavior. I can work around it, but it just seems odd, so I was wondering if someone could explain why I get the following output:
> xlabs <- 1:367
> i <- c(2:5)
> Date[xlabs == i]
character(0)
Warning message:
In xlabs == i :
longer object length is not a multiple of shorter object length
> Date[xlabs = i]
[1] "2011-07-19" "2011-07-20" "2011-07-21" "2011-07-22"
I don't understand why the logical equals does not apply in this instance, but the simple equals does. I am writing a quick manual for how to do a certain analysis process in R, and I don't want to have to use a "just because" explanation for my readers' sake.
Upvotes: 0
Views: 526
Reputation: 174778
The operator you want is %in%
:
Date[xlabs %in% i]
The =
isn't doing what you think it is. Look at xlabs
after the last line of your example; you are setting xlabs
to be i
as if you did xlabs <- i
as =
is almost a replacement for <-
.
The ==
doesn't work because of the way it is doing comparisons. Consider:
> 1:10 == 5:7
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
Warning message:
In 1:10 == 5:7 :
longer object length is not a multiple of shorter object length
That is doing:
> 1 == 5
[1] FALSE
> 2 == 6
[1] FALSE
> 3 == 7
[1] FALSE
> 4 == 5
[1] FALSE
> 5 == 6
[1] FALSE
> 6 == 7
[1] FALSE
> 7 == 5
[1] FALSE
> 8 == 6
[1] FALSE
> 9 == 7
[1] FALSE
> 10 == 5
[1] FALSE
R recycles the shorter vector by repeating it to match the length of the longer. As length(xlabs)
is not an exact multiple of length(i)
you get the warning, but it is the comparisons themselves that are not selecting anything
> 1[FALSE]
numeric(0)
hence the empty vector (in your case an empty character vector).
Upvotes: 4