I do not understand the following code. Why are the following two objects not identical?
a <- dim(matrix(nrow=1, ncol=1)); a
# [1] 1 1
identical(a, c(1,1))
# FALSE
CodePudding user response:
Because dim
returns an integer vector. However, c(1, 1)
is a floating point vector. Unfortunately the difference can’t be seen simply by printing their values but you can inspect the class
of the values, which will show as integer
and numeric
(= floating point numbers), respectively.
To get the same result, do the following:
identical(a, c(1L, 1L))
# [1] TRUE
CodePudding user response:
When you type ?identical
, you will see
The safe and reliable way to test two objects for being exactly equal. It returns TRUE in this case, FALSE in every other case.
However, c(1,1)
gives a numeric
array, but dim
returns the integer
one, which is not exactly the same class.
You can try all.equal
, which checks the "near equality", e.g.,
> all.equal(a,c(1,1))
[1] TRUE