Getting a character from a string

Basic types / Character type

text <- "ABC"

# A string has no index: use substr()
char_a <- substr(text, 1, 1)
# char_a = A
char_b <- substr(text, 2, 2)
# char_b = B
char_c <- substr(text, 3, 3)
# char_c = C

# The last one: count from the length
last_pos <- nchar(text)
char_last <- substr(text, last_pos, last_pos)
# char_last = C

# Several positions at once
positions <- seq_len(last_pos)
chars <- substring(text, positions, positions)
# chars = A B C

# Past the end: an empty string, not an error
beyond <- substr(text, 4, 4)
# beyond =

# text[2] is not a char: the string is one element
second <- text[2]
# second = NA

cat("char_a =", char_a, "\n")
cat("char_b =", char_b, "\n")
cat("char_c =", char_c, "\n")
cat("char_last =", char_last, "\n")
cat("chars =", chars, "\n")
cat("beyond =", beyond, "\n")
cat("second =", second, "\n")