[R] substr gives empty output

Howard, Tim G (DEC) tim.howard at dec.ny.gov
Mon Jan 22 13:58:27 CET 2018


In 

 y <- substr(x, i, 1)

your third integer needs to be the location not the number of digits, so change it to 

 y <- substr(x, i, i)

and you should get what you want. 
Cheers, 
Tim

> Date: Sun, 21 Jan 2018 10:50:31 -0500
> From: Ek Esawi <esawiek at gmail.com>
> To: Luigi Marongiu <marongiu.luigi at gmail.com>, r-help at r-project.org
> Subject: Re: [R] substr gives empty output
> Message-ID:
>         <CA+ZkTxubYDSZ3iqsg_=be9HBA2_3-TE95=mXbh4atvG-
> ri_ixQ at mail.gmail.com>
> Content-Type: text/plain; charset="UTF-8"
> 
> The reason you get "" is, as stated on the previous response and on the
> documentation of substr function, the function "When extracting, if start is
> larger than the string length then "" is returned.". This is what happens on
> your function.
> 
> HTH
> 
> EK
> 
> On Sun, Jan 21, 2018 at 3:59 AM, Luigi Marongiu <marongiu.luigi at gmail.com>
> 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)
> > }
> >
> >         [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> 
> 



More information about the R-help mailing list