Chris Wesseling
Chris Wesseling

Reputation: 6368

Is everything a vector in R?

I have dabbled with Pandas in Python doing some manipulations and regressions on data I collected and answering SO questions, and thought learning the inspiration of it might help my understanding.

I'm using the learn-R tutorial and after vector and some digging on SO and the web, I come to this:

# So assigning a value to v will create an atomic vector
# of length one with a type
v <- 1
is.vector(v)  # TRUE
class(v)  # 'numeric'
# But literals are also vectors? These all return TRUE
is.vector(1)
is.vector("string literal")
is.vector(TRUE)
is.vector("c")

# and lists are vectors too
l <- list(1, 2, 3)
is.vector(l)  # TRUE

So is everything a vector in R?

Upvotes: 3

Views: 1109

Answers (1)

user2554330
user2554330

Reputation: 44877

No, some things are not vectors in R, but most ways you would want to store data are vectors. Confusing the issue is that is.vector() has a weird definition: it doesn't allow attributes. For example,

x <- 1:3
is.vector(x)
#> [1] TRUE
attr(x, "foo") <- "bar"
x
#> [1] 1 2 3
#> attr(,"foo")
#> [1] "bar"
is.vector(x)
#> [1] FALSE

Created on 2021-09-07 by the reprex package (v2.0.0)

I would say that x is still a vector even with the attribute, but the is.vector() function thinks things with attributes aren't vectors. For a ridiculous example: according to is.vector(), factors aren't vectors, but you can treat them as if they are:

x <- factor(letters[1:4])
is.vector(x)
#> [1] FALSE
x
#> [1] a b c d
#> Levels: a b c d
x[2:3]
#> [1] b c
#> Levels: a b c d

Created on 2021-09-07 by the reprex package (v2.0.0)

So if we define vectors to be objects that can be indexed using [] or [[]], then most data types (types built from logical, integer, numeric, complex, character and raw, as well as lists) are vectors. There are no scalars of those types in R.

On the other hand, if you define vectors to be objects for which is.vector() returns TRUE, there are lots of data types that aren't vectors: factors, matrices, arrays, time series, data.frames, etc. So don't do that. :-)

Your examples using literals work that way because R doesn't treat literal values in any special way. They are just expressions that give objects.

Some things really aren't vectors: the NULL object, language objects like names (e.g. as.name("x")), environments, functions, etc.

Upvotes: 5

Related Questions