OneBite.Dev - Coding blog in a bite size

loop through each character in a string in R

Code snippet on how to loop through each character in a string in R

  str <- "Hello World"
  for (i in 1:nchar(str)) {
    print(substr(str, i, i))
  }

This code loops over the characters in a string, one by one. The first line assigns the string ‘Hello World’ to the variable ‘str’. The for loop then iterates over the characters, from 1 to the length of the string (which is 11 characters long). The substr command takes the string and extracts the single character at each position in the loop, which is then printed. After the loop is complete, all 11 characters in the string have been printed out.

r