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

`````` 3
``````

``
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.
`3`
, i.e. just a number)

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

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

`A[1,]`
: 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? Martin

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)
 TRUE
> is.atomic(1 + 2)
 TRUE
> length(1 + 2)
 1
``````

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

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

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

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

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