rfunctionvectortoupper

Creating a function in R that capitalizes ONLY the first n elements of a vector


I want to create a function (v,n) where v is a vector of string values and n is an integer number. This function should capitalize only the first n elements of the vector. And if n is greater than the length(v), it should capitalize all the elements in the vector.

So if I have: v = c("a","b","c","d") and n = 3, the function should return:

[1]   ("A", "B", "C", "d")

So far, I have this:

function(v, n){
  if(n <= length(v))
  {i = seq_len(n)
  v[i]= toupper(v[i])}
  return(v)} 

But when I try it to apply it to a vector (using sapply):

test = sapply(v, function, n=3)

Nothing happens. None of the elements in the vector are capitalized


Solution

  • toupper is a vectorized function so you don't need a loop or any of the apply functions.

    v = c("a","b","c","d")
    
    capitilize_n <- function(vec, n) {
      n <- min(n, length(vec))
      inds <- seq_len(n)
      vec[inds] <- toupper(vec[inds])  
      return(vec)
    }
    
    capitilize_n(v, 3)
    #[1] "A" "B" "C" "d"
    
    capitilize_n(v, 8)
    #[1] "A" "B" "C" "D"