Consider the following code:
test <- function(n)
{
for(x in 1:n)
{
for(y in 1:n)
{
for(r in max(x-1,1):min(x+1,n))
{
for(s in max(y-1,1):min(y+1,n))
{
vec <- c(x-r,y-s)
print(c("vec = ", vec))
print(identical(vec,c(0,0)))
}
}
}
}
}
If you run test(2) you'll see a printout of the values of the vector vec
followed by a logical telling you whether vec is identical to c(0,0), which
it will be for certain iterations of the nested loop. However, the logical
is always FALSE. If I don't perform the loop but instead assign the values
directly to vec, this problem does not arise. Can anyone tell me what is
happening here?
Thank you very much in advance for any help.
--
View this message in context: http://r.789695.n4.nabble.com/Odd-behaviour-of-identical-tp4630118.html
Sent from the R help mailing list archive at Nabble.com.
Odd behaviour of identical()
3 messages · math_daddy, R. Michael Weylandt
I believe it's coming down to the difference between integers and doubles (the computer data types, not the math-y meaning of those terms) -- e.g., identical( c(0L, 0L), c(0,0) ) Note that sequences made by `:` provide integers when possible: is.integer(1:5) You may want to use all.equal() instead. Best, Michael
On Tue, May 15, 2012 at 11:45 AM, math_daddy <math_daddy at hotmail.com> wrote:
Consider the following code:
test <- function(n)
{
?for(x in 1:n)
?{
? ?for(y in 1:n)
? ?{
? ? ?for(r in max(x-1,1):min(x+1,n))
? ? ?{
? ? ? ?for(s in max(y-1,1):min(y+1,n))
? ? ? ?{
? ? ? ? ?vec <- c(x-r,y-s)
? ? ? ? ?print(c("vec = ", vec))
? ? ? ? ?print(identical(vec,c(0,0)))
? ? ? ?}
? ? ?}
? ?}
?}
}
If you run test(2) you'll see a printout of the values of the vector vec
followed by a logical telling you whether vec is identical to c(0,0), which
it will be for certain iterations of the nested loop. However, the logical
is always FALSE. If I don't perform the loop but instead assign the values
directly to vec, this problem does not arise. Can anyone tell me what is
happening here?
Thank you very much in advance for any help.
--
View this message in context: http://r.789695.n4.nabble.com/Odd-behaviour-of-identical-tp4630118.html
Sent from the R help mailing list archive at Nabble.com.
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Thanks. I was not aware of these subtleties of R, but then again I'm no expert. I had to use isTRUE(all.equal(vec,c(0,0))), but it seems to be working now. Thanks again. -- View this message in context: http://r.789695.n4.nabble.com/Odd-behaviour-of-identical-tp4630118p4630170.html Sent from the R help mailing list archive at Nabble.com.