[R] substr gives empty output

Ted Harding ted.harding at wlandres.net
Sun Jan 21 10:35:08 CET 2018


On Sun, 2018-01-21 at 09:59 +0100, Luigi Marongiu wrote:
> Dear all,
> I have a string, let's say "testing", and I would like to extract in
> sequence each letter (character) from it. But when I use substr() I only
> properly get the first character, the rest is empty (""). What am I getting
> wrong?
> For example, I have this code:
> 
> >>>
> x <- "testing"
> k <- nchar(x)
> for (i in 1:k) {
>   y <- substr(x, i, 1)
>   print(y)
> }

>From the help page
  substr(x, start, stop)
where 'start' is the position in the character vector x at which the
substring starts, and 'stop' is the position at which it stops.

Hence 'stop' must be >= 'start'; and if they are equal then you get
just the single character. That is the case in your code, when i=1;
when i > 1 then stop < start, so you get nothing. Compare with:

  x <- "testing"
  k <- nchar(x)
  for (i in 1:k) { 
    y <- substr(x, i, i)  ### was: substr(x, i, 1)
    print(y)
  }

[1] "t"
[1] "e"
[1] "s"
[1] "t"
[1] "i"
[1] "n"
[1] "g"

Hoping this helps,
Ted.



More information about the R-help mailing list