Removing a character from within a vector element
r
Solution
You can use `nchar` to find the length of each element of the vector
> nchar(str.vect)
[1] 6 6 6 6
Then you combine this with `strtrim` to get the beginning of each string
> strtrim(str.vect, nchar(str.vect)-3)
[1] "abc" "abc" "abc" "abc"
To get the end of the word you can then use `substr` (actually, you could use substr to get the beginning too...)
> substr(str.vect, nchar(str.vect)-1, nchar(str.vect))
[1] ".1" ".1" ".2" ".2"
And finally you use `paste0` (which is `paste` with `sep=""`) to stick them together
> 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 easier ways if you know your strings have some special characteristics
For instance, if the length is always 6 you can directly substitute the `nchar` calls with the appropriate value.
EDIT: alternatively, R also supports regular expressions, which make this task much easier.
> gsub(".(..)$", "\\1", str.vect)
[1] "abc.1" "abc.1" "abc.2" "abc.2"
The syntax is a bit more obscure, but not that difficult once you know what you are looking at.
The first parameter (`".(..)$"`) is what you want to match
`.` matches any character, `$` denotes the end of the string. So `...$` indicates the last 3 characters in the string.
We put the last two in parenthesis, so that we can store them in memory.
The second parameter tells us what you want to substitute the matched substring with. In our case we put `\\1` which means "whatever was in the first pair of parenthesis".
So essentially this command means: "find the last three characters in the string and change them with the last two".
Problem
I have a vector of strings: `str.vect<-c ("abcR.1", "abcL.1", "abcR.2", "abcL.2")` ``` str.vect [1] "abcR.1" "abcL.1" "abcR.2" "abcL.2" ``` How can I remove the third character from the right in each vector element? Here is the desired result: `"abc.1" "abc.1" "abc.2" "abc.2"` Thank you very much in advance