Character vector exercises

December 18, 2015
By

(This article was first published on R-exercises, and kindly contributed to R-bloggers)

character vectorsIn the exercises below we cover the basics of character vectors. Before proceeding, first read section 2.6 of An Introduction to R, and the help pages for the nchar, substr and sub functions.

Answers to the exercises are available here.

Exercise 1
If x <- “Good Morning! “, find out the number of characters in X
a. 1
b. 14
c. 13

Exercise 2
Consider the character vector x <- c (“Nature’s”, “Best “), how many characters are there in x?
a. 12
b. 13
c. 8,5

Exercise 3
If x <- c("Nature’s"," At its best ") , how many characters are there in x?
a. 19
b. 8, 15
c. 8, 9

Exercise 4
If fname <- “James“ and lname <- “Bond”, write some R code that will produce the output "James Bond".

Exercise 5
If m <- “Capital of America is Washington” then extract the string “Capital of America” from the character vector m.

Exercise 6
Write some R code to replace the first occurrence of the word “failed” with “failure” in the string “Success is not final, failed is not fatal”.

Exercise 7
Consider two character vectors:
Names <- c("John", "Andrew", "Thomas") and
Designation <- c("Manager", "Project Head", "Marketing Head").
Write some R code to obtain the following output.
Names Designation
1 John Manager
2 Andrew Project Head
3 Thomas Marketing Head

Exercise 8
Write some R code that will initialise a character vector with fixed length of 10.

Exercise 9
Write some R code that will generate a vector with the following elements, without using loops.
"aa" "ba" "ca" "da" "ea" "ab" "bb" "cb" "db" "eb" "ac" "bc" "cc" "dc" "ec"
"ad" "bd" "cd" "dd" "ed" "ae" "be" "ce" "de" "ee"

Exercise 10
Let df <- data.frame(Date = c("12/12/2000 12:11:10")) . Write some R code that will convert the given date to character values and gives the following output:
"2000-12-12 12:11:10 GMT"

To leave a comment for the author, please follow the link and comment on their blog: R-exercises.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)