i doing r exercise:
write function splits string letters , return min & max letters according alphabetical order.
here's vector:
cities <- c("new york", "paris", "london", "tokyo", "rio de janeiro", "cape town") here's code have written:
first_and_last <- function(name){ name <- gsub (" ", "", name) letters <- strsplit(name, split = "") c(first = min(letters), last = max(letters)) } however, got errors when run it:
first_and_last(cities) #error in min(letters) (from #4) : invalid 'type' (list) of argument kindly let me know what's missing in code? thanks!
i assuming want element-wise operation, i.e., each element of cities, extract first , last letter in alphabetic order. 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(). return min , max. r's built-in implementation function(x) c(min(x), max(x)).
follow-up
thanks, problem solved. i'm taking online course in r. in solution, used following line of code. if possible please explain, line of code mean. especially, double bracket part "[[1]]":
letters <- strsplit(name, split = "")[[1]]
strsplit returns list. let's try:
strsplit("bath", split = "") #[[1]] #[1] "b" "a" "t" "h" if want access character vector, need [[1]]:
strsplit("bath", split = "")[[1]] #[1] "b" "a" "t" "h" only vector can take min / max. 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 online example see takes single character. if have 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 want apply range each list element, sapply 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 based on sapply. yet nice presentation, have transposed result , given row / column names.
gosh, realize sked question on [[]] 2 days ago: double bracket [[]] within function. why still asking me explanation???
Comments
Post a Comment