[R] clipping off words inside a vector of strings
Marc Schwartz
marc_schwartz at comcast.net
Mon Oct 15 18:22:17 CEST 2007
On Mon, 2007-10-15 at 12:04 -0400, Gonçalo Ferraz wrote:
> Hi,
>
> I have a vector of strings (class character) with 6 elements (length
> 6). I call it 'names'.
>
> "Graham Chapman"
> "John Cleese"
> "Terry Gilliam"
> "Eric Idle"
> "Terry Jones"
> "Michael Palin"
>
> And I want to turn it into another vector of strings called
> 'shortnames' with the same length.
> The new vector should look like:
>
> "Gra Cha"
> "Joh Cle"
> "Ter Gil"
> "Eri Idl"
> "Ter Jon"
> "Mic Pal"
>
> I just want to clip the first three characters of each word inside
> each string.
>
> Would anyone know how to do this quickly?
>
> Thanks!
>
> Gonalo
How about this:
> HolyGrail
[1] "Graham Chapman" "John Cleese" "Terry Gilliam" "Eric Idle"
[5] "Terry Jones" "Michael Palin"
> gsub("^(.{3}).+ (.{3}).+", "\\1 \\2", HolyGrail)
[1] "Gra Cha" "Joh Cle" "Ter Gil" "Eri Idl" "Ter Jon" "Mic Pal"
See ?gsub and ?regex
HTH,
Marc Schwartz
A reading from the Book of Armaments, Chapter 4, Verses 16 to 20:
Then did he raise on high the Holy Hand Grenade of Antioch, saying,
"Bless this, O Lord, that with it thou mayst blow thine enemies to tiny
bits, in thy mercy." And the people did rejoice and did feast upon the
lambs and toads and tree-sloths and fruit-bats and orangutans and
breakfast cereals ... Now did the Lord say, "First thou pullest the Holy
Pin. Then thou must count to three. Three shall be the number of the
counting and the number of the counting shall be three. Four shalt thou
not count, neither shalt thou count two, excepting that thou then
proceedeth to three. Five is right out. Once the number three, being the
number of the counting, be reached, then lobbest thou the Holy Hand
Grenade in the direction of thine foe, who, being naughty in my sight,
shall snuff it."
-- Monty Python, "Monty Python and the Holy Grail"
More information about the R-help
mailing list