I am assuming you want element-wise operation, i.e., for each element of cities
, extract the first and last letter in alphabetic order. This is what you need:
first_and_last <- function(name){
name <- gsub (" ", "", name)
myName <- strsplit(name, split = "")
result <- t(sapply(myName, range)) ## use function `range`
rownames(result) <- name
colnames(result) <- c("first", "last")
return(result)
}
first_and_last(cities)
# first last
# New York "e" "Y"
# Paris "a" "s"
# London "d" "o"
# Tokyo "k" "y"
# Rio de Janeiro "a" "R"
# Cape Town "a" "w"
I have used function range()
. This will return min
and max
. It is R's built-in implementation for function(x) c(min(x), max(x))
.
Follow-up
Thanks, problem solved. I'm taking an online course in R. In their solution, they used the following line of code. If possible could you please explain, what does this line of code mean. Especially, the double bracket part "[[1]]": letters <- strsplit(name, split = "")[[1]]
strsplit
returns a list. Let's try:
strsplit("Bath", split = "")
#[[1]]
#[1] "B" "a" "t" "h"
If you want to access the character vector, you need [[1]]
:
strsplit("Bath", split = "")[[1]]
#[1] "B" "a" "t" "h"
Only with a vector you can take min
/ max
. For example:
min(strsplit("Bath",split=""))
#Error in min(strsplit("Bath", split = "")) :
# invalid 'type' (list) of argument
min(strsplit("Bath",split="")[[1]])
#[1] "a"
I believe the online example you see only takes a single character. If you have a vector input like:
strsplit(c("Bath", "Bristol", "Cambridge"), split = "")
#[[1]]
#[1] "B" "a" "t" "h"
#[[2]]
#[1] "B" "r" "i" "s" "t" "o" "l"
#[[3]]
#[1] "C" "a" "m" "b" "r" "i" "d" "g" "e"
and you want to apply range
for each list element, sapply
will be handy:
sapply(strsplit(c("Bath", "Bristol", "Cambridge"), split = ""), range)
# [,1] [,2] [,3]
#[1,] "a" "B" "a"
#[2,] "t" "t" "r"
My function first_and_last
above is based on sapply
. Yet for nice presentation, I have transposed the result and given row / column names.
Gosh, I just realize you already sked a question on [[]]
2 days ago: Double Bracket [[]] within a Function. So why are you still asking me for explanation???