Home > Back-end >  How to create a function that extracts the last n letters of strings contained in a vector
How to create a function that extracts the last n letters of strings contained in a vector

Time:11-16

I'm starting to program in R and I have to create a final function that receives a vector v of character strings and an integer n, and returns another vector of the same length as v that in each position contains a string with only the n last letters of the original string.

In addition I have to use the function substr (ch, start_pos, end_pos) and also the nchar function that returns the length (number of letters) of a character string. Apply it to the vector test defined below to check its operation by extracting the last 3 letters of each word, and save the result in the variable final.test. It is not necessary to take into account the case that the string is itself less than the number of final letters that we want to take.

Cannot use loops or sapply / lapply.

That is, I have to create a function that, when introducing a vector, for example c ("Hola", "que", "tal"), returns "la", "ue", "al" if we put that vector and we give n the value 2 (that starts counting from the end and stops and extracts at n).

I tried to do this:

finales <- function(v, n){
  substr = substr(v, nchar(v[1:n]), n)
  return(substr)
}

But it returns this to me:

> finales(prueba,3)
[1] ""   "s"  "n"  ""   "e"  "ad" ""   "ar"

And it is not exactly what I am looking for but I do not know how to determine what has to count from the end of each element of the vector to the number that we will introduce in the function (n).

The function would have to pass these tests:

prueba = c("Esto", "es", "un", "vector", "de", "cadenas", "de", "caracteres")
length(finales(prueba, 3)) == length(prueba)
all(finales(prueba, 3) == c('sto', 'es', 'un','tor','de','nas','de','res'))

If you could help me I would be enormously grateful

CodePudding user response:

substr is vectorised, so you can have:

final <- function(v, n) substr(v, nchar(v) - (n - 1), nchar(v))

So, for example:

final(prueba, 1)
#> [1] "o" "s" "n" "r" "e" "s" "e" "s"

final(prueba, 2)
#> [1] "to" "es" "un" "or" "de" "as" "de" "es"

final(prueba, 3)
#> [1] "sto" "es"  "un"  "tor" "de"  "nas" "de"  "res"

Created on 2021-11-15 by the reprex package (v2.0.0)

  • Related