[R] [FORGED] substr gives empty output

Rolf Turner r.turner at auckland.ac.nz
Sun Jan 21 10:17:25 CET 2018

On 21/01/18 21:59, 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?

What you're getting wrong is failing the read the help for substr(). 
The third argument is "stop", not the length of the substring.

> For example, I have this code:
> x <- "testing"
> k <- nchar(x)
> for (i in 1:k) {
>    y <- substr(x, i, 1)
>    print(y)
> }

You want y <- substr(x,i,i).


Rolf Turner

Technical Editor ANZJS
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276

More information about the R-help mailing list