text <- "ABC"
# 字符串不能按索引取字符:用 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
# 最后一个:从长度算起
last_pos <- nchar(text)
char_last <- substr(text, last_pos, last_pos)
# char_last = C
# 一次取多个位置
positions <- seq_len(last_pos)
chars <- substring(text, positions, positions)
# chars = A B C
# 超出末尾:得到空字符串,而不是报错
beyond <- substr(text, 4, 4)
# beyond =
# text[2] 不是字符:整个字符串是一个元素
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")