Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using R please provide the Code for a-d. R has a built-in character vector of US

ID: 3348608 • Letter: U

Question

Using R please provide the Code for a-d. R has a built-in character vector of US State names, state.name. Use this character vector and R's character functions to answer the following questions.Show R code

(a) List all the US State names that are more than one word. How many are there?

(b) What is the longest US State name(s) (including spaces) and how long is it?

(c) What is the longest single word US State name and how long is it?

(d) List all the US State names, where all of the upper and lower case “a"s are replaced with a capital “Z".

Explanation / Answer

(a) List all the US State names that are more than one word. How many are there?

Answer)

I use here the grep function on the vector state.name which search for spaces in a string in the element of the vectors,which indicate more than one word element, then I check for the length which shows how many element are there with more than one word.
state.name is the vector name present in R. In grep function value=TRUE means it will display the elements in the vector.

grep(" ",state.name,value=TRUE)

length(grep(" ",state.name,value=TRUE))

or

grep(" ",state.name,value=TRUE);length(grep(" ",state.name,value=TRUE))

or

grep(" ",state.name,value=TRUE);paste("Total number of Multi word state is: ",length(grep(" ",state.name,value=TRUE)))

(b) What is the longest US State name(s) (including spaces) and how long is it?

Answer)


state.name[nchar(state.name)==max(nchar(state.name))];max(nchar(state.name))

or

paste('Longest Strings is ',state.name[nchar(state.name)==max(nchar(state.name))]);paste( "Longest length is ", max(nchar(state.name)))

(c) What is the longest single word US State name and how long is it?

Answer

I just reverse by invert=TRUE the grep, so it find elements in vector which does not had spaces. I take the output of grep in a vector v.Then I count by nchar function which count the elements in a vector.

v=grep(" ",state.name,value=TRUE,invert=TRUE);
v[nchar(v)==max(nchar(v))]

The below will return the length

max(nchar(v))

(d) List all the US State names, where all of the upper and lower case “a"s are replaced with a capital “Z".

Answer)

First I find with grep then ,gsub I use for replace a or A with Z.


gsub("a|A","Z",grep("a|A",state.name,value=TRUE))

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote