Video Notes
In R, it’s common to see output in the console that starts with [1]. E.g.:
Even simply executing our objects (x or y) will produce this same output:
What does this [1] mean and why is it there?
Everything is a Vector by Default
To understand why we see this [1], note that in R everything is a vector by default, unless explicitly structured otherwise (e.g., as a list or data frame).
A vector in R is the most fundamental data structure, used to store a sequence of values of the same data type.
When we define a single string ("hello") or numeric value (123), we’re actually creating vectors that contain just a single value.
As evidence of this, check out the following code where we have R confirm x is a vector and tells us its length:
x <- "hello"
is.vector(x) # TRUE
length(x) # 1
Understanding this, when we output x or y using the print function, the [1] we’re seeing in the console is just indicating the index of the elements we’re looking at. In these examples, there’s just a single element, so that index is always [1].
Let’s contrast this to longer vectors, such as a sequence of numbers. As an example we’ll generate a random sample of 100 numbers between 1 and 9:
random_numbers <- sample(1:9, size = 100, replace = TRUE)
print(random_numbers)
The output of the above is something like this:
[1] 4 7 4 1 4 5 9 8 3 5 5 8 4 8 1 6 4 5 1 8 9 5 7 5 6 1 2 7 5 7
[31] 4 6 6 9 9 6 9 6 2 2 8 7 7 3 2 1 1 8 7 1 1 6 7 6 6 2 3 8 8 2
[61] 4 3 5 1 1 1 1 5 6 3 1 6 3 4 7 8 1 7 4 1 1 2 3 2 4 8 2 2 9 3
[91] 6 6 4 7 5 7 7 5 2 6
The [1] on the first lines indicates we’re seeing values starting at the 1st position.
The [16] on the second line indicates we’re seeing values starting at the 16th position.
Etc.
The index positions provided by the print function just helps provide us with context of what part of our vector we’re looking at.
Avoiding indexed output
If we wanted to see just our values without an index position, we could instead use R’s cat function as another way to output our data:
Code:
random_numbers <- sample(1:9, size = 100, replace = TRUE)
cat(random_numbers)
Output:
3 8 8 2 6 9 4 7 4 9 8 8 4 3 9 9 9 9 8 4 3 7 4 7 6 4 3 5 4 3 9 7 6 6 3 8 2 6 5 7 1 5 9 8 4 5 3 5 1
5 3 3 7 7 1 1 7 9 4 1 8 9 2 4 9 6 8 6 7 2 9 4 9 1 3 3 7 3 2 8 5 3 9 3 8 9 5 5 1 6 6 8 1 8 5 6 6 3
6 5
Code:
x <- 'hello'
cat(x)
Output:
hello
Implicit Printing
Returning to our introduction, we also noted that even just executing a line that references x will produce the indexed output:
This happens because when an object is referenced directly, R automatically invokes the print function on that object. This is a technique known as implicit printing.
In short, invoking x
is the equivalent of invoking print(x)
.