Iterating over a string

Basic types / Strings

word <- "code"

# A string is one value: split it into characters
chars <- strsplit(word, "")[[1]]

# The loop takes the elements, no index needed
# prints c, o, d, e one per line
for (ch in chars) {
  cat(ch, "\n")
}

# Each character with its index
numbered <- paste(seq_along(chars), chars)

# Reverse iteration
# prints e, d, o, c one per line
for (ch in rev(chars)) {
  cat(ch, "\n")
}

cat("numbered =", numbered, "\n")
# numbered = 1 c 2 o 3 d 4 e