Loop with Character Vector in R (Example)

 

In this tutorial you’ll learn how to loop through a character string vector in R programming.

The article consists of the following information:

It’s time to dive into the example.

 

Introducing Example Data

We use the following data as basement for this R programming language tutorial:

my_vec <- letters[1:5]        # Create example vector
my_vec                        # Print example vector
# "a" "b" "c" "d" "e"

Have a look at the previous output of the RStudio console. It shows that our example data is a character vector containing five alphabetical letters ranging from “a” to “e”.

 

Example: Looping Through Character Vector

In this Example, I’ll show how to loop over the elements of our character vector. For this, we have to specify our character vector within the head of our for-loop.

Note that this is possible, because for-loops in R are not iterating over a regular sequence of numbers, but over a collection of objects.

for(i in my_vec) {            # Head of for-loop
  print(i)                    # Body of for-loop
}
# [1] "a"
# [1] "b"
# [1] "c"
# [1] "d"
# [1] "e"

The previous for-loop is simply printing the character used as index in each of the iterations.

 

Video & Further Resources

Do you want to know more about looping over characters? Then you may want to watch the following video of my YouTube channel. In the video, I illustrate the contents of this article in a live session:

 

The YouTube video will be added soon.

 

Furthermore, you might read the other tutorials of https://www.statisticsglobe.com/. A selection of posts can be found below.

 

To summarize: At this point you should have learned how to for-loop over a character string in R. In case you have further questions, let me know in the comments.

 



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.

Menu
Top