[R] drop last character in a names'vector

Greg Snow Greg.Snow at imail.org
Sat May 1 00:58:18 CEST 2010


The nchar and substring functions are both vectorized, you can do something like:

> substring(state.name, 1, nchar(state.name)-1)

And it should be much faster.


-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Sebastian Kruk
> Sent: Friday, April 30, 2010 4:45 PM
> To: r-help at r-project.org; r-help at stat.math.ethz.ch
> Subject: [R] drop last character in a names'vector
> 
> Hi, i have a vector filled with names:
> 
> [1] Alvaro Adela ...
> [25] Beatriz Berta ...
> ...
> [100000] ...
> 
> I would like to drop last character in every name.
> 
> I use the next program:
> 
> for (i in 1:100000) {
>                           largo <- nchar(names[i]-1)
>                           names[i] <- substring (names[i],1,largo]
>                          }
> 
> Is another and faster way of do it?
> 
> Thanks,
> 
> Sebastián.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> 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