Removing a character from a vector element

I have a row vector:

str.vect<-c ("abcR.1", "abcL.1", "abcR.2", "abcL.2")

 str.vect
[1] "abcR.1" "abcL.1" "abcR.2" "abcL.2"

How to remove the third character on the right in each vector element?

Here is the desired result:

"abc.1" "abc.1" "abc.2" "abc.2"

Thank you in advance

+4
source share
5 answers

You can use ncharto search the length of each element of the vector

> nchar(str.vect)
[1] 6 6 6 6

Then you combine this with strtrimto get the beginning of each line

> strtrim(str.vect, nchar(str.vect)-3)
[1] "abc" "abc" "abc" "abc"

To get the end of a word, you can use substr(in fact, you can use substr to get a start too ...)

> substr(str.vect, nchar(str.vect)-1, nchar(str.vect))
[1] ".1" ".1" ".2" ".2"

And finally, you use paste0(which pastec sep="") to connect them

> paste0(strtrim(str.vect, nchar(str.vect)-3), # Beginning
         substr(str.vect, nchar(str.vect)-1, nchar(str.vect))) # End
[1] "abc.1" "abc.1" "abc.2" "abc.2"

There are simpler ways if you know your lines have some special characteristics.

, 6, nchar .


EDIT: R , .

> gsub(".(..)$", "\\1", str.vect)
[1] "abc.1" "abc.1" "abc.2" "abc.2"

, , , .

(".(..)$") - ,

. , $ . , ...$ 3 .

, .

, . \\1, ", ".

, : " ".

+9

, @nico, , sub:

sub('.(.{2})$', '\\1', str.vect)

: " ( .), 2 ( .{2}), ( $)". .{2} , R . - . , . \\1. ( , , , , \\2, \\3 ..)

+5
str.vect<-c ("abcR.1", "abcL.1", "abcR.2", "abcL.2")

a <- strsplit(str.vect,split="")

a <- strsplit(str.vect,split="")
b <- unlist(lapply(a,FUN=function(x) {x[4] <- ""
                          paste(x,collapse="")}
                          ))

, 4 , .

+3

, , , , :

( nico, strtrim.)

my.string <- c("abcR.1", "abcL.1", "abcR.2", "abcL.2")

n.char <- nchar(my.string)
the.beginning <- substr(my.string, n.char-(n.char-1), n.char-3)
the.end <- substr(my.string, n.char-1, n.char)

new.string <- paste0(the.beginning, the.end)
new.string

# [1] "abc.1" "abc.1" "abc.2" "abc.2"
+1

.

sapply(str.vec, function(x)  gsub(substr(x, nchar(x)-2,nchar(x)-2), "", x))
0
source

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


All Articles