taupe117 taupe117 - 3 years ago 198
R Question

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
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?

  • 1 + 2
    , i.e. just a number)

  • c(1,-2,3,14)

  • A = matrix(c(1,-2,3,14),2,2)

    : this is the first line of the matrix. Is it a (1, 2) single-row matrix or just a vector or a list?

  • A[,2]
    : this is the second column of the matrix. Is it a (2, 1) single-column matrix or just a vector or a list?

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

Answer Source

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)
> is.atomic(A)
[1] TRUE
> is.vector(A[1, ])
[1] TRUE
> is.atomic(A[1, ])
[1] TRUE
> is.matrix(A[1, ])
> is.vector(A[, 2])
[1] TRUE
> is.atomic(A[, 2])
[1] TRUE
> is.matrix(A[, 2])

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download