R: cut a string of characters in vectors

let x be a vector

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

Is it possible to create a vector, say y , from x st its components

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

?

In other words, I need a command in R that cuts the lines of text by a given length (in the above, length = 5).

Thanks a lot!

+7
source share
3 answers

More obvious than substring for me would be strtrim :

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

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

The second argument, widths , can be a width vector of the same length as the input vector, in which case each element can be cut off by a certain amount.

 > strtrim(x, c(1, 2, 3)) [1] "h" "he" "Nya" 
+10
source

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" 
+6
source

using: sprintf() :

 sprintf("%.*s", 5, x) [1] "hi" "hello" "Nyarl" 
0
source

Source: https://habr.com/ru/post/1500679/


All Articles