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.
The operator you want is
%in%:The
=isn’t doing what you think it is. Look atxlabsafter the last line of your example; you are settingxlabsto beias if you didxlabs <- ias=is almost a replacement for<-.The
==doesn’t work because of the way it is doing comparisons. Consider:That is doing:
R recycles the shorter vector by repeating it to match the length of the longer. As
length(xlabs)is not an exact multiple oflength(i)you get the warning, but it is the comparisons themselves that are not selecting anythinghence the empty vector (in your case an empty character vector).