Repeat Character String N Times in R (2 Examples)

 

In this tutorial, I’ll explain how to repeat the elements of a character string multiple times in R programming.

The tutorial will contain two examples for the repetition of strings. More precisely, the content looks as follows:

Let’s start right away!

 

Creation of Example Data

The first step is to create some data that we can use in the examples later on:

my_string <- "ABC"          # Create example character string
my_string                   # Print example character string
# [1] "ABC"

Have a look at the previous output of the RStudio console. It shows that our example data is a character string object containing the alphabetical letters “ABC”.

 

Example 1: Repeat & Concatenate Character String to Single Data Object

The following syntax explains how to repeat a character string N times and concatenate it in the same element.

Have a look at the following R code and its output:

strrep(my_string, 5)        # Repeat & concatenate
# [1] "ABCABCABCABCABC"

As you can see, the RStudio console has returned a single character string that contains our input character string (i.e. “ABC”) five times.

 

Example 2: Repeat Character String & Store in Vector Object

Example 2 explains how to create a vector where an input character string is repeated as multiple vector elements:

rep(my_string, 5)           # Repeat & create vector
# [1] "ABC" "ABC" "ABC" "ABC" "ABC"

As you can see based on the previous output, we have created a vector with five vector elements. Each of these elements contains the character string “ABC”.

 

Video & Further Resources

Do you want to learn more about character strings in R? Then I recommend watching the following video of my YouTube channel. I show the R programming syntax of this article in the video instruction.

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

In addition, you could read some of the other articles of my homepage. Some tutorials are listed below:

 

Summary: In this R tutorial you have learned how to replicate a character string several times. In case you have additional questions, please let me know in the comments section. Besides that, please subscribe to my email newsletter to receive updates on the newest articles.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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