How to for-Loop Over Character String Vector in R (Example Code)

In this R programming tutorial you’ll learn how to for-loop over a character string.

Creation of Example Data

my_char <- c("XXX", "a", "ABC", "d")                                             # Creating character vector
my_char                                                                          # Printing character vector
# "XXX" "a"   "ABC" "d"

Example: for-Loop Over Character Vector in R

for(index in my_char) {                                                          # for-looping over character vector
  print(paste("The current iteration is based on the character string", index))  # Create some output
}
# [1] "The current iteration is based on the character string XXX"
# [1] "The current iteration is based on the character string a"
# [1] "The current iteration is based on the character string ABC"
# [1] "The current iteration is based on the character string d"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top