# Hacking strings with stringr

July 14, 2017
By

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This is first of the set of exercise on string manipulation with stringr

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Exercise 1
use a stringr function to merge this 3 strings .
`x <- "I AM SAM. I AM SAM. SAM I AM" `
`y <- "THAT SAM-I-AM! THAT SAM-I-AM! I DO NOT LIKE THAT SAM-I-AM!"`
`z <- ""DO WOULD YOU LIKE GREEN EGGS AND HAM?"`

Exercise 2

Now use a vector which contains x,y,z and NA and make it a single sentence using paste ,do the same by the same function you used for exercise1 .Can you spot the difference .

Exercise 3

Install the babynames dataset ,find the vector of length of the babynames using stringr functions. You may wonder nchar can do the same so why not use that ,try finding out the difference and let me know in the comments.

Exercise 4

We often use substr to get part of the string ,in stringr world there exist a much powerful function which does almost the same thing . Create a string name with your name .
Use str_sub to get the last character and the last 5 characters .

Exercise 5

In mtcars dataset rownames, find all cars of the brand Merc .

Learn more about Text analysis in the online course Text Analytics/Text Mining Using R. In this course you will learn how create, analyse and finally visualize your text based data source. Having all the steps easily outlined will be a great reference source for future work.

Exercise 6

Use the same mtcars rownames ,find the total number of times “e” appears in that .

Exercise 7

Suppose you have a string like this
` j <- "The_quick_brown_fox_jumps_over_the_lazy_dog" `
split it in words using a stringr function

Exercise 8

On the same string I need the first word splitted but the rest intact ,help me to achieve that

Exercise 9

Now for on the same string J
a> I want the first “_” replaced by “–”
b> I want all the “_” replaced by “–”

Exercise 10

Many of the times ,you don’t want `NA` to appear when you do some string manipulation but its sometimes necessary to replace NA as a character(rather than remove it) ,stringr provides a useful tool for that.
Now if I have a vector like this ,
na_string_vec <- c("The_quick_brown_fox_jumps_over_the_lazy_dog",NA)

How can you turn the NA into a character string .

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.