1.5.1 If x <- “Good Morning! “, find out the number of characters in X
x <- c("Good Morning! ")
nchar(x)
## [1] 14
1.5.2 Consider the character vector x <- c (“Nature’s”, “Best “), how many characters are there in x?
x2 <- c ("Nature’s", "Best ")
nchar(x2)
## [1] 8 5
nchar function gives the number of characters of each character member of the vector. so thats why the result is 8+5 (notice the spaces)
1.5.3 If x <- c(“Nature’s”," At its best “) , how many characters are there in x?
x3 <- c("Nature’s"," At its best ")
nchar(x3)
## [1] 8 13
1.5.4 If fname <- “James“ and lname <- “Bond”, write some R code that will produce the output”James Bond“.
fname <- "Kung"
lname <- "Fury"
paste(fname, lname)
## [1] "Kung Fury"
1.5.5 If m <- “Capital of America is Washington” then extract the string “Capital of America” from the character vector m.
m <- "Capital of America is Washington"
## substr(vector, start = start, stop = stop)
substr(m, 1, 18)
## [1] "Capital of America"
1.5.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”.
text <- "Success is not final, failed is not fatal"
sub("failed", "failure", text)
## [1] "Success is not final, failure is not fatal"
1.5.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
Names <- c("John", "Andrew", "Thomas")
Designation <- c("Manager", "Project Head", "Marketing Head")
data.frame(Names, Designation)
## Names Designation
## 1 John Manager
## 2 Andrew Project Head
## 3 Thomas Marketing Head
1.5.8 Write some R code that will initialise a character vector with fixed length of 10.
test <- vector(mode="character", length = 10)
test
## [1] "" "" "" "" "" "" "" "" "" ""
1.5.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”
c(outer(letters[1:5], letters[1:5], FUN=paste, sep=""))
## [1] "aa" "ba" "ca" "da" "ea" "ab" "bb" "cb" "db" "eb" "ac" "bc" "cc" "dc"
## [15] "ec" "ad" "bd" "cd" "dd" "ed" "ae" "be" "ce" "de" "ee"
## I have started with thinkink like this honestly: paste(letters[1:5],"a"....)
1.5.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”
Date = c("12/12/2000 12:11:10")
Date2 = strptime(Date, "%m/%d/%Y %H:%M:%S")
Date2
## [1] "2000-12-12 12:11:10 CET"
*For the last exercise, check this website for more information: https://www.stat.berkeley.edu/~s133/dates.html*