Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: cut string of characters in vectors

Tags:

text

r

vector

let x be the vector

[1] "hi"            "hello"         "Nyarlathotep"

Is it possible to produce a vector, let us say y, from x s.t. its components are

[1] "hi"            "hello"         "Nyarl"

?

In other words, I would need a command in R which cuts strings of text to a given length (in the above, length=5).

Thanks a lot!

like image 258
Avitus Avatar asked Sep 05 '13 08:09

Avitus


2 Answers

Use substring see details in ?substring

> x <- c("hi", "hello", "Nyarlathotep")
> substring(x, first=1, last=5)
[1] "hi"    "hello" "Nyarl"

Last update You can also use sub with regex

> sub("(.{5}).*", "\\1", x)
[1] "hi"    "hello" "Nyarl"
like image 199
Jilber Urbina Avatar answered Oct 21 '22 21:10

Jilber Urbina


More obvious than substring to me would be strtrim:

> x <- c("hi", "hello", "Nyarlathotep")
> x
[1] "hi"           "hello"        "Nyarlathotep"
> strtrim(x, 5)
[1] "hi"    "hello" "Nyarl"

substring is great for extracting data from within a string at a given position, but strtrim does exactly what you're looking for.

The second argument is widths and that can be a vector of widths the same length as the input vector, in which case, each element can be trimmed by a specified amount.

> strtrim(x, c(1, 2, 3))
[1] "h"   "he"  "Nya"
like image 30
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 21 '22 22:10

A5C1D2H2I1M1N2O1R2T1