Sunday, 14 January 2018

How to Test the Equality of Vectors in R Programming

Testing Vector Equality
We can Test the equality of vectors using the vectorized function '==', along with the all() function.
In general, we can test the equality of  elements , by the following way.
> "=="(3,2)

> i <- 2
> "=="(i,2)
[1] TRUE

But if we wish to test whether two vectors are equal, using the '==' , it won't work , like the above.
> x <- 1:3
> y <- c(1,3,4)
> x == y


In fact, == is a vectorized function. The expression x == y applies the function ==() to the elements of x and y. yielding a vector of Boolean values.
Now we can test the equality of vectors using the all() function.
> all(x == y)

Applying all() to the result of == asks whether all of the elements of the Vector are true, which is the same as asking whether x and y are identical. We can simply use the identical function, like this:
> identical(x,y)

> x <- 1:2
> y <- c(1,2)

> x
[1] 1 2
> y
[1] 1 2

> identical(x,y)

> typeof(x)
[1] "integer"
> typeof(y)
[1] "double"

The Colon : produces integers while c() produces floating-point numbers.

Vector Element Names or Element Headers:
The elements of a vector can optionally be given names. For example, say we have a 50-element vector showing the population of each state in the United States. We could name each element according to its state name, such as "Montana" and "New Jersey". This in turn might lead to naming points in plots, and so on.

We can assign or query vector element names via the names() function:
x <- c(1,2,4)
> names(x)

> names(x) <- c("a","b","ab")
> names(x)
[1] "a" "b" "ab"

> x
a  b  ab
1  2  4

We can remove the names from a vector by assigning NULL.
> names(x) <- NULL
> x
[1] 1 2 4

We can even reference elements of the vector by name.
> x <- c(1,2,4)
> names(x) <- c("a","b","ab")
> x["b"]

Another point to keep in mind is that c() has a flattening effect for vectors,as in this example:
> c(5,2,c(1.5,6))
[1] 5.0 2.0 1.5 6.0 

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your open Feedback only related to this Blog Posts. Please note that I cannot respond to the Anonymous Comments.

Subscribe to Blog Posts by Email

ExcelKingdom-Popular Posts