To reverse a string in R, you can use the strsplit()
function to split the string into individual characters, then reverse the resulting list, and finally concatenate the characters back into a string.
In this example,
str1
with a value of 'Hello World'
.str1
into a list of characters using strsplit()
.paste()
and print the result.str1 <- 'Hello World'
char_list <- unlist(strsplit(str1, ''))
reversed_str1 <- paste(rev(char_list), collapse='')
cat('Reversed string is: ', reversed_str1)
Reversed string is: dlroW olleH
In this example,
str2
with a value of 'apple'
.str2
into a list of characters using strsplit()
.paste()
and print the result.str2 <- 'apple'
char_list <- unlist(strsplit(str2, ''))
reversed_str2 <- paste(rev(char_list), collapse='')
cat('Reversed string is: ', reversed_str2)
Reversed string is: elppa
In this tutorial, we learned How to Reverse a String in R language with well detailed examples.