(Named) Lists & character vectors

Last update on

Invalid Date

During the last years, I heavily rely on using (named) lists and/or character vectors. What is a character or a character vector? A character is a string It is created using single quotes or double quotes.

myChr <- "Hi I am string"

It is possible to combine (c(...)) multiple characters into a vector or a list.

myChr1 <- "Hi I am string"
myChr2 <- "Hi I am string, too"

myChr <- c(myChr1, myChr2)

(Named) Lists

What is a list in R? Lists are objects which contain any type of other R objects (e.g., characters, numeric inputs).

myList <- list(myChr,
               "Hi Iam another string",
               3)

Sometimes1 it is advisable to name the list elements.

myNamedList <- list(MyChr = myChr,
                    String3 = "Hi Iam another string",
                    "Number 3" = 3)

names(myNamedList) <- c("MyChr", "String3", "Number 3")

Or alternatively.

names(myList) <- c("MyChr", "String3", "Number 3")

Creating character vectors

The paste and paste0 functions are extremely powerful functions. They convert R objects to character vectors. With the sep= and collapse= arguments, it is possible to select specific character strings which separates/collapse the objects. It is important to note that the functions behave slightly different (see here). The focus here is on paste0 which sets sep="".

myName <- "John Doe"

paste0(c("hello, my name is ", myName), collapse = " <3 ")

[1] “hello, my name is <3 John Doe”

We can use the paste0 function to create the names of the variables (of a measure)2. The variable names should follow a precise structure3 see Table 1.

Table 1: Overview of the Structure of Variable Names
Abbreviation of measure Item Number Measurement occasion
Self-concept > sc 1 T1
Self-concept > sc 2 T1
Self-concept > sc 3 T1
Self-concept > sc 1 T2
Self-concept > sc 2 T2

paste0 function

list("ScT1" = paste0("sc", 1:3, "T1"),
     "ScT2" = paste0("sc", 1:3, "T2"))
$ScT1
[1] "sc1T1" "sc2T1" "sc3T1"

$ScT2
[1] "sc1T2" "sc2T2" "sc3T2"

If you are really laze you could also write.

paste0("sc", 1:3, rep(paste0("T", 1:2), each = 3))
[1] "sc1T1" "sc2T1" "sc3T1" "sc1T2" "sc2T2" "sc3T2"

Footnotes

  1. It is especially advisable when you want to automate table or plot generation see e.g., here↩︎

  2. It is important to point out, that it might be reasonable to import the codebook instead of creating the variable names by yourself↩︎

  3. On how to create codebooks see e.g. DataWiz Knowledge Base.↩︎