How to fine-tune each element in a row vector?

I have a vector:

v <- c("godzilla", "jurassic", "googly")

I need the first 3 letters of each element in this vector. I would like to end up with:

# "god"   "jur"   "goo"

I already tried using apply, but it did not work. What should I do?

+4
source share
3 answers

One parameter substring():

> substring(v, first = 1, last = 3)
[1] "god" "jur" "goo"

as well as version R, substr()

> substr(v, start = 1, stop = 3)
[1] "god" "jur" "goo"

Note the different names for the desired start and last characters.

Since both of these functions are vectorized, there is no need for apply()friends here either .

+7
source

For fun, you can use regex here:

sub('(^.{3}).*','\\1',v)
[1] "god" "jur" "goo"

This is another vector solution.

+5
source

@ Gavin Simpson - , apply() , :

> sapply(strsplit(v, ""), function(x) paste0(x[1:3], collapse=""))
[1] "god" "jur" "goo"
+2

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


All Articles