Post

Values, Vectors, and Lists in R

A participant’s record needs to associate an identifier with scores from several visits, including visits with no measurement. Combining all these values in one R vector can turn the scores into text, making arithmetic impossible. How can we organize the record while preserving what each value means and which calculations it supports? We begin with numeric vectors and examine how types, lengths, and missing values affect their operations. We then select and replace particular scores before combining them with other participant information in a list.

2.1 Values, names, and assignment

When seconds is 90, minutes <- seconds / 60 stores 1.5. If seconds changes to 120, minutes is still 1.5. Repeating the assignment updates minutes to 2. At the Console, a name entered by itself displays its current value.

1
2
3
seconds <- 90
minutes <- seconds / 60
minutes
1
[1] 1.5

The same assignment can name a collection of values, such as a participant’s scores at three visits. A vector is an ordered collection of values called elements. The function c() combines values into a vector. Here, c(2, 4, 5) records the three visit scores in order, and scores names the whole vector. In the display, [1] means that the line begins with the first element.

1
2
scores <- c(2, 4, 5)
scores
1
[1] 2 4 5

length() counts elements. Its argument here is a vector of visit scores, the number 2, or the duration stored in seconds.

1
2
3
length(scores)
length(2)
length(seconds)
1
2
3
[1] 3
[1] 1
[1] 1

In R, a single number such as 2 is a vector of length one. The duration in seconds also has one element, while scores has three.

The association between a name and its value is called a binding. working <- scores creates another binding to the same vector value. At this point, either name retrieves the three visit scores.

1
2
3
working <- scores
scores
working
1
2
[1] 2 4 5
[1] 2 4 5

If working now refers to 9, what does scores refer to?

1
2
3
working <- 9
scores
working
1
2
[1] 2 4 5
[1] 9

The assignment changes the binding for working. The three elements of scores are still 2, 4, and 5.

The record also needs an identifier that says whose scores these are. As text, the participant identifier "0007" has four characters. Without the quotation marks, R reads 0007 as the number 7. length() counts the identifier as one element. nchar() counts the four characters in it.

1
2
3
4
5
participant_id <- "0007"
participant_id
0007
length(participant_id)
nchar(participant_id)
1
2
3
4
[1] "0007"
[1] 7
[1] 1
[1] 4

2.2 Types, coercion, and attributes

If a vector of scores includes the word "absent", can you still add a point to every score? The answer depends on the type R uses for the combined values. We can inspect the basic types with typeof() before combining them. Logical values represent true or false. The L suffix requests integer storage for a whole number. R stores 1 as a double, a type that can also represent fractions. Quotation marks make "1" character data.

1
2
3
4
typeof(TRUE)
typeof(1L)
typeof(1)
typeof("1")
1
2
3
4
[1] "logical"
[1] "integer"
[1] "double"
[1] "character"

An atomic vector is a vector whose elements all have one type. Every vector used so far is atomic. When c() combines inputs of different types, it may convert them to a common type, a process called coercion. In c(TRUE, 5), the logical value and the number have to share a storage type.

1
2
3
mixed <- c(TRUE, 5)
mixed
typeof(mixed)
1
2
[1] 1 5
[1] "double"

R stores 5 as a double, so it converts TRUE to 1 to give both elements the same type. In this coercion, FALSE would become 0. R made the conversion without a message.

Here c() combines the three numeric scores with "absent". The vector needs one type, and text can represent both the scores and the label.

1
2
3
scores_text <- c(scores, "absent")
scores_text
typeof(scores_text)
1
2
[1] "2"      "4"      "5"      "absent"
[1] "character"

The quotation marks around "2", "4", and "5" show that even the scores are now text. The + operator cannot add 1 to this vector.

1
2
# Deliberate error: arithmetic on a character vector
scores_text + 1
1
Error in scores_text + 1 : non-numeric argument to binary operator

as.numeric() can convert text that represents a number. Here it takes a new vector containing only "2", "4", and "5" and returns the three scores as a double vector.

1
2
3
converted <- as.numeric(c("2", "4", "5"))
converted
typeof(converted)
1
2
[1] 2 4 5
[1] "double"

The string "unknown" does not represent a number.

1
2
# Deliberate diagnostic: text that is not a number
as.numeric("unknown")
1
2
3
[1] NA
Warning message:
NAs introduced by coercion

The addition to scores_text stopped with an error. This conversion completes and returns NA, R’s marker for an unavailable value. The warning says that R introduced it when converting "unknown".

Visit labels need not become elements alongside the scores. An attribute associates information with an object separately from its values. The name scores refers to the whole vector, while its names attribute labels the individual scores. Assigning c("visit_1", "visit_2", "visit_3") to names(scores) identifies each visit without converting the scores to text.

1
2
3
4
5
names(scores) <- c("visit_1", "visit_2", "visit_3")
scores
names(scores)
typeof(scores)
length(scores)
1
2
3
4
5
visit_1 visit_2 visit_3 
      2       4       5 
[1] "visit_1" "visit_2" "visit_3"
[1] "double"
[1] 3

The visit labels changed how the scores are displayed, but typeof(scores) still reports double. Another way to inspect an object is class(), which gives the classification that many functions use to decide how to handle it. Type and class need not have the same name: the scores have storage type double and class numeric. For the integer and logical examples below, the two names are the same.

1
2
3
4
5
6
typeof(scores)
class(scores)
typeof(1L)
class(1L)
typeof(TRUE)
class(TRUE)
1
2
3
4
5
6
[1] "double"
[1] "numeric"
[1] "integer"
[1] "integer"
[1] "logical"
[1] "logical"

2.3 Vector arithmetic and length

measurements contains the three visit scores without their names. measurements + 1 adds a point at each position and returns the adjusted scores as a new vector. If the adjustments vary by visit, which one goes with each score?

1
2
measurements <- c(2, 4, 5)
measurements + 1
1
[1] 3 5 6

R pairs adjustments with scores by position. In measurements + c(10, 20, 30), 10 goes with 2, 20 with 4, and 30 with 5. Each adjustment must be in the same position as its intended visit.

1
measurements + c(10, 20, 30)
1
[1] 12 24 35

An adjustment vector can be shorter than the values it modifies. To see what happens when its pattern repeats exactly, consider four values and two adjustments, 10 and 20. What does R add to the third value? Table 2.1 shows the pairings.

1
2
values <- c(1, 2, 3, 4)
values + c(10, 20)
1
[1] 11 22 13 24

Table 2.1. Recycling two adjustments across four values.

PositionValueAdjustment usedResult
111011
222022
331013
442024

R repeats 10 for the third value and 20 for the fourth. This reuse of a shorter vector is called recycling. It also explains why adding 1 adjusts every score. Since four is an exact multiple of two, R gives no warning, even if the fourth value was supposed to receive an adjustment other than 20.

For the original three measurements, the same pair of adjustments cannot complete its second cycle. This changes whether R issues a warning, although the adjustments are still matched by position.

1
2
# Deliberate warning: lengths 3 and 2
measurements + c(10, 20)
1
2
3
4
[1] 12 24 15
Warning message:
In measurements + c(10, 20) :
  longer object length is not a multiple of shorter object length

The third measurement received 10, producing 15. R returned all three values and warned because the second cycle stopped halfway through. If the adjustments were meant to alternate, 15 is the expected score for the third visit.

2.4 Comparisons, logical vectors, and missing values

Suppose the third visit has no measurement. Which visits can we say had a score above 3? In recorded <- c(2, 4, NA), NA marks the place of the missing score. The vector still has type double, and recorded > 3 tests each position against the cutoff.

1
2
3
4
recorded <- c(2, 4, NA)
recorded
typeof(recorded)
recorded > 3
1
2
3
[1]  2  4 NA
[1] "double"
[1] FALSE  TRUE    NA

The first two answers are FALSE and TRUE because 2 is below 3 and 4 is above it. For the third visit, NA means the score could be above 3 or it could be 3 or lower.

Testing recorded == NA, where == asks whether two values are equal, does not locate the missing position. Equality with an unknown value is also unknown, even for a known measurement such as 2.

1
2
# A comparison that cannot locate missing values
recorded == NA
1
[1] NA NA NA

is.na(recorded) tests each position for a missing value. It returns TRUE for the third position and FALSE for the two observed measurements.

1
is.na(recorded)
1
[1] FALSE FALSE  TRUE

Suppose completed <- c(TRUE, TRUE, FALSE) records whether each visit was completed. Which visits were completed and had a score above 3? The & in recorded > 3 & completed requires both conditions to be true at the same position.

1
2
3
4
completed <- c(TRUE, TRUE, FALSE)
recorded > 3 & completed
FALSE & NA
TRUE & NA
1
2
3
[1] FALSE  TRUE FALSE
[1] FALSE
[1] NA

The third visit was incomplete, so it cannot satisfy both conditions, whatever its score. That is why FALSE & NA gives FALSE. With TRUE & NA, the answer still depends on the unknown condition.

Which visits scored above 3 or were incomplete? ! reverses each completion flag, so !completed is true for an incomplete visit. The | in recorded > 3 | !completed asks whether at least one of those two conditions is true.

1
2
3
recorded > 3 | !completed
TRUE | NA
!(recorded > 3)
1
2
3
[1] FALSE  TRUE  TRUE
[1] TRUE
[1]  TRUE FALSE    NA

The third visit qualifies because it was incomplete. One known TRUE is enough for TRUE | NA to give TRUE. Reversing just the score comparison with !(recorded > 3) still gives NA for that visit.

The third comparison is unknown, but it still occupies a position in recorded > 3.

1
2
length(recorded)
length(recorded > 3)
1
2
[1] 3
[1] 3

That position is essential when the elements represent successive visits. NA marks a missing measurement and has length one, whereas NULL has length zero. In c(2, NA, 5), the missing second score has a position of its own. In c(2, NULL, 5), NULL contributes no element, so 5 becomes the second score.

1
2
3
4
length(NA)
length(NULL)
c(2, NA, 5)
c(2, NULL, 5)
1
2
3
4
[1] 1
[1] 0
[1]  2 NA  5
[1] 2 5

Undefined arithmetic such as 0 / 0 can produce NaN, short for not a number. In the vector below, NA marks a missing measurement and NaN is the result of that division. is.nan() tests specifically for NaN.

1
2
3
4
5
6
7
undefined <- 0 / 0
undefined
unavailable <- c(NA, undefined)
unavailable
is.na(unavailable)
is.nan(unavailable)
unavailable > 3
1
2
3
4
5
[1] NaN
[1]  NA NaN
[1] TRUE TRUE
[1] FALSE  TRUE
[1] NA NA

is.nan() identifies only the result of 0 / 0, while is.na() identifies both entries as unavailable. Both comparisons with 3 give NA. A rule that selects only observed scores above 3 would exclude these entries because neither has a score to compare.

2.5 Selecting and replacing vector elements

The three scores in measurements are 2, 4, and 5. Suppose the first should be 3. Before changing it, we can retrieve that score with measurements[1]. The number in brackets is its position, called an index. R counts from 1, and retrieving one position returns a one-element vector.

1
2
measurements[1]
length(measurements[1])
1
2
[1] 2
[1] 1

The three elements of scores are named visit_1, visit_2, and visit_3. scores["visit_2"] retrieves the second visit’s score by name. A vector of positions selects elements in the requested order. After scores[c(3, 1, 2)] puts the third visit first, which score does the name visit_2 retrieve?

1
2
3
4
5
scores["visit_2"]
reordered <- scores[c(3, 1, 2)]
reordered
reordered[1]
reordered["visit_2"]
1
2
3
4
5
6
7
8
visit_2 
      4 
visit_3 visit_1 visit_2 
      5       2       4 
visit_3 
      5 
visit_2 
      4 

After reordering, position 1 has the third visit’s value, 5, while the name visit_2 retrieves 4, as before. A position depends on order; the name still identifies the same visit.

Positions can also specify elements to exclude. The negative index in measurements[-2] excludes the second element and returns the remaining values without changing measurements.

1
measurements[-2]
1
[1] 2 5

A logical index can specify which scores to select. If there is one TRUE or FALSE per score, R selects the scores marked TRUE. Here measurements > 3 marks the second and third positions, so putting that condition inside brackets retrieves 4 and 5.

1
2
measurements > 3
measurements[measurements > 3]
1
2
[1] FALSE  TRUE  TRUE
[1] 4 5

On its own, measurements[1] retrieves the first score. On the left of <-, the same index tells R which score to replace. Assigning 3 there corrects the first visit’s score without changing the other two.

1
2
measurements[1] <- 3
measurements
1
[1] 3 4 5

The example starts again from the original scores, 2, 4, and 5. After working <- measurements, both names refer to those scores. Does replacing working[1] also change measurements[1]?

1
2
3
4
5
measurements <- c(2, 4, 5)
working <- measurements
working[1] <- 3
measurements
working
1
2
[1] 2 4 5
[1] 3 4 5

Ordinary R vectors follow a rule called copy-on-modify. After working <- measurements, the two names can refer to the same vector. Replacing working[1] gives working a modified copy with 3 in the first position. The first score in measurements is still 2.

In recorded, the third visit has no score. What happens to that visit when we use recorded > 3 to select scores?

1
2
recorded > 3
recorded[recorded > 3]
1
2
[1] FALSE  TRUE    NA
[1]  4 NA

The TRUE position contributes 4. The unknown position contributes NA because R cannot tell whether the missing score qualifies.

To select only observed scores above 3, the condition also needs a test for an observed value. At the third visit, !is.na(recorded) is FALSE, so the combined condition is FALSE.

1
2
3
!is.na(recorded) & recorded > 3
recorded[!is.na(recorded) & recorded > 3]
recorded
1
2
3
[1] FALSE  TRUE FALSE
[1] 4
[1]  2  4 NA

The only selected score is 4. The last line shows that the third position in recorded is still missing.

2.6 Lists and components of different types

A participant record might contain the identifier "0007", the three visit scores 2, 4, and 5, and a completion flag of TRUE. Can we store them together and still add a point to each score? c() puts all five values in a single vector.

1
2
3
flattened <- c("0007", 2, 4, 5, TRUE)
flattened
typeof(flattened)
1
2
[1] "0007" "2"    "4"    "5"    "TRUE"
[1] "character"

Combining the values with c() converted the scores and flag to text. The resulting vector marks no boundary between the identifier, the three scores, and the completion flag. A list is a vector whose components can each be any object, including another list.

list() collects objects as components, each with its own type and length. Here each component has a name, id, responses, or completed. A named component is often called a field. The display introduces each field with $ and its name.

1
2
3
4
responses <- c(2, 4, 5)
participant <- list(id = "0007", responses = responses, completed = TRUE)
participant
typeof(participant)
1
2
3
4
5
6
7
8
9
10
$id
[1] "0007"

$responses
[1] 2 4 5

$completed
[1] TRUE

[1] "list"

length(participant) counts the fields in the record. length(responses) counts the scores in the vector assigned to the responses field. Both happen to be 3 in this example.

1
2
length(participant)
length(responses)
1
2
[1] 3
[1] 3

Single brackets applied to a list return another list. participant["responses"] has just one component, even though that component contains three scores.

1
2
3
participant["responses"]
length(participant["responses"])
typeof(participant["responses"])
1
2
3
4
5
$responses
[1] 2 4 5

[1] 1
[1] "list"

Adding a point to each score requires the numeric vector inside the list. Double brackets extract that vector. What happens if we try the same addition with single brackets?

1
2
3
participant[["responses"]]
length(participant[["responses"]])
participant[["responses"]] + 1
1
2
3
[1] 2 4 5
[1] 3
[1] 3 5 6
1
2
# Deliberate error: arithmetic on a one-component list
participant["responses"] + 1
1
2
Error in participant["responses"] + 1 : 
  non-numeric argument to binary operator

Adding 1 to the extracted vector gives 3, 5, and 6. With single brackets, R tries to add 1 to a list and reports an error. participant$responses is another way to extract the three scores by name.

1
participant$responses
1
[1] 2 4 5

A field can itself contain several related fields. Contact details provide an example. Assigning a new component named contact adds a list containing email and city, so participant now has four components. participant$contact$city first retrieves the contact list, then retrieves city from that list. The equivalent double-bracket path is participant[["contact"]][["city"]].

1
2
3
participant$contact <- list(email = "p0007@example.com", city = "Seoul")
participant$contact
participant$contact$city
1
2
3
4
5
6
7
$email
[1] "p0007@example.com"

$city
[1] "Seoul"

[1] "Seoul"

The record has no age field, so participant$age returns NULL. is.null() tests for that result. After with_age <- participant, does adding an age field to with_age also change participant?

1
2
3
4
5
6
7
8
participant$age
is.null(participant$age)
with_age <- participant
with_age$age <- NA
with_age$age
is.na(with_age$age)
length(participant)
length(with_age)
1
2
3
4
5
6
NULL
[1] TRUE
[1] NA
[1] TRUE
[1] 4
[1] 5

R lists also follow copy-on-modify. After adding age to with_age, participant still has its original four fields. The new field belongs to with_age, which now has five fields. Its NA means that the field exists and the age is unknown.

This post is licensed under CC BY-NC 4.0 by the author.