user4381653
user4381653

Reputation:

Vector vs. List vs. Single-row matrix vs. Single-column matrix with R

When entering this in the R console:

1 + 2

we get, as an answer:

[1] 3

Does the leading [1] mean "The output is a matrix, and the elements in the first line of this matrix are: 3" ?

More generally, are these objects a vector, a list, a single-row matrix or a single-column matrix?

I've already read the documentation a few times, but I was wondering if there exists a rule of thumb to remember this?

Upvotes: 1

Views: 280

Answers (1)

Martin
Martin

Reputation: 46

Basically, for checking the data types in R, you can use several functions contained in the base package.

Now, focusing on your explicit questions:

> is.vector(1 + 2)
[1] TRUE
> is.atomic(1 + 2)
[1] TRUE
> length(1 + 2)
[1] 1

Consequently, the result is stored in a vector of length 1.

> is.vector(c(1,-2,3,14))
[1] TRUE
> is.atomic(c(1,-2,3,14))
[1] TRUE

As c(...) initializes a vector object, obviously the data type is a vector.

> is.matrix(A)
[1] TRUE
> is.vector(A)
[1] FALSE
> is.atomic(A)
[1] TRUE
> is.vector(A[1, ])
[1] TRUE
> is.atomic(A[1, ])
[1] TRUE
> is.matrix(A[1, ])
[1] FALSE
> is.vector(A[, 2])
[1] TRUE
> is.atomic(A[, 2])
[1] TRUE
> is.matrix(A[, 2])
[1] FALSE

And finally, subsetting a matrix row-wise or column-wise returns also a vector and not a matrix.

For checking for a scalar, please refer to this question.

Edit:

As mentioned by @Rich Scriven, there are two types of vectors in R: atomic and generic vectors. Indeed, the function is.vector(x) used in above examples returns TRUE for lists as well. Besides that, is.atomic(x) checks for atomic vectors which contain data of one primitive data type (logical, integer, real, complex, character, or raw) only. Additionally, I have added the respective is.atomic(x) function calls in above examples as well.

Upvotes: 2

Related Questions