0

I created a function for simples characters... my function completes a character with zeros while the number of character is less(strictly) that 4.

completamento<- function(c)
{
  while( nchar(c)< 4)
   {
     c<- paste0("0",c)
   }
return(c)
}   

When I do

completamento(c="aaa")
> "0aaa"

It is OK...

But when I try to put the argument of the function to be one vector, there is some wrong..

completamento(c=c("aaa", "bb"))
Warning messages:
1: In while (nchar(c) < 4) { :
   the condition has length > 1 and only the first element will be used
2: In while (nchar(c) < 4) { :
   the condition has length > 1 and only the first element will be used

There is some way to vectorize this function?

MAOC
  • 625
  • 2
  • 8
  • 26
  • 1
    A quick fix `completamento<- function(c) { for (i in 1:length(c)) { if(nchar(c[i]) < 4) { c[i] <- paste0("0", c[i]) } } return(c) } ` – s_baldur Oct 10 '16 at 21:44
  • It's a solution. But I allways avoid to use the looping for in my scripts.. – MAOC Oct 10 '16 at 21:57
  • @Vasco - a `while()` statement is just a loop too. – thelatemail Oct 10 '16 at 22:54
  • Yes.. there is some way to avoid the while function? Or in other words, I would to like use the minimal loop functions... – MAOC Oct 10 '16 at 22:56
  • Some one put this solution and deleted it: completamento <- Vectorize(completamento, USE.NAMES = F) – MAOC Oct 10 '16 at 23:05

0 Answers0