Skip to content

Working with string

6 messages · Christofer Bogaso, Bert Gunter, Marc Schwartz +1 more

#
Hello again,

Let say I have following string:

Vec <- c("sada", "asdsa", "sa")

Now I want to make each element of this vector with equal length.
Basically I want following vector:

c("sada ", "asdsa", "sa   ")

Therefore we can get:
[1] 5 5 5


Is there any possiblity that we can do it programetically? Because I
need to handle a really big vector.

Thanks for your help.
#
library(stringr)
?str_pad(Vec,5,"right")
#[1] "sada " "asdsa" "sa?? "


#or
str_pad(Vec,max(nchar(Vec)),"right")
#[1] "sada " "asdsa" "sa?? "



str_count(str_pad(Vec,5,"right"),"")
#[1] 5 5 5
A.K.


----- Original Message -----
From: Christofer Bogaso <bogaso.christofer at gmail.com>
To: r-help <r-help at r-project.org>
Cc: 
Sent: Thursday, March 14, 2013 10:42 AM
Subject: [R] Working with string

Hello again,

Let say I have following string:

Vec <- c("sada", "asdsa", "sa")

Now I want to make each element of this vector with equal length.
Basically I want following vector:

c("sada ", "asdsa", "sa?  ")

Therefore we can get:
[1] 5 5 5


Is there any possiblity that we can do it programetically? Because I
need to handle a really big vector.

Thanks for your help.

______________________________________________
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.
#
On Mar 14, 2013, at 9:42 AM, Christofer Bogaso <bogaso.christofer at gmail.com> wrote:

            
?format will by default, left justify and pad with spaces to the longest length element in the character vector:

Vec <- c("sada", "asdsa", "sa")
[1] "sada " "asdsa" "sa   "


Regards,

Marc Schwartz
#
In addition to Marc's suggestion:
sprintf("%-5s",Vec)
#[1] "sada " "asdsa" "sa?? "
?formatC(Vec,width=-5)
#[1] "sada " "asdsa" "sa?? "
formatC(Vec,width=5)
#[1] " sada" "asdsa" "?? sa"
format(Vec,justify="right")
#[1] " sada" "asdsa" "?? sa"
A.K.



----- Original Message -----
From: Marc Schwartz <marc_schwartz at me.com>
To: Christofer Bogaso <bogaso.christofer at gmail.com>
Cc: r-help <r-help at r-project.org>
Sent: Thursday, March 14, 2013 11:02 AM
Subject: Re: [R] Working with string
On Mar 14, 2013, at 9:42 AM, Christofer Bogaso <bogaso.christofer at gmail.com> wrote:

            
?format will by default, left justify and pad with spaces to the longest length element in the character vector:

Vec <- c("sada", "asdsa", "sa")
[1] "sada " "asdsa" "sa?  "


Regards,

Marc Schwartz

______________________________________________
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.