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!
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With