library(stringr)
<- function(x) {
mystring str_sub(x, 1, 3)
}mystring(words[1:10])
[1] "a" "abl" "abo" "abs" "acc" "acc" "ach" "acr" "act" "act"
Jeffrey R. Stevens
March 27, 2023
mystring
that takes a vector as an argument and returns the first three characters from the string. Test it on words[1:10]
. [1] "a" "abl" "abo" "abs" "acc" "acc" "ach" "acr" "act" "act"
mystring()
that allows the user to control how many of the first characters should be returned. Test it on words[1:10]
with 5 characters. [1] "a" "able" "about" "absol" "accep" "accou" "achie" "acros" "act"
[10] "activ"
mystring()
to be 3 and test that the default works and that you can override the default. [1] "a" "abl" "abo" "abs" "acc" "acc" "ach" "acr" "act" "act"
[1] "a" "able" "about" "absol" "accep" "accou" "achie" "acros" "act"
[10] "activ"
stop()
function to stop the computation and return a message to the console telling the user that the vector was not a character vector. Test your function with a character vector, a numeric vector, and a logical vector.mystring <- function(x, chars = 3) {
if (!is.character(x)) {
stop("Please enter a character vector.")
} else {
str_sub(x, 1, chars)
}
}
mystring(words[1:10])
[1] "a" "abl" "abo" "abs" "acc" "acc" "ach" "acr" "act" "act"
parse_my_vector
that does the following:type
that determines whether the vector is a numeric ("num"
), character ("char"
), or logical ("logical"
) vector. There should be no default value. If the user response does not match any of these three strings, stop with a message asking the user to specify one of the three strings.parse_my_vector <- function(x, type) {
if (type == "num") {
if (is.numeric(x)) {
output <- x / 10
} else {
stop("Type response does not match vector type.")
}
} else if (type == "char") {
if (is.character(x)) {
output <- str_sub(x, 1, 3)
} else {
stop("Type response does not match vector type.")
}
} else if (type == "logical") {
output <- sum(x)
} else {
stop("Please enter either 'num', 'char', or 'logical'.")
}
message("Thank you!")
list(x,output)
}
parse_my_vector()
:Thank you!
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
[[2]]
[1] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
# parse_my_vector(x = 1:10, type = "char")
# parse_my_vector(x = words[1:10], type = "num")
parse_my_vector(x = words[1:10], type = "char")
Thank you!
[[1]]
[1] "a" "able" "about" "absolute" "accept" "account"
[7] "achieve" "across" "act" "active"
[[2]]
[1] "a" "abl" "abo" "abs" "acc" "acc" "ach" "acr" "act" "act"
# parse_my_vector(x = c(TRUE, FALSE, TRUE), type = "num")
parse_my_vector(x = c(TRUE, FALSE, TRUE), type = "logical")
Thank you!
[[1]]
[1] TRUE FALSE TRUE
[[2]]
[1] 2