Reputation: 77
I have a character vector as shown below and I want only the first and last letter from each value in this vector that should be separated by a dash (-).
df <- c("bcdefg", "abc", "bcdefg", "abcd", "abcdefg", "abc", "a")
The result should be like this
[1] "b-g" "a-c" "b-g" "a-d" "a-g" "a-c" "a"
Any code to do this in the R program. I would be thankful for your help.
Upvotes: 0
Views: 300
Reputation: 388862
A base R option using sub
using two capture groups.
df <- c("bcdefg", "abc", "bcdefg", "abcd", "abcdefg", "abc", "a")
sub('^(.).*(.)$', '\\1-\\2', df)
#[1] "b-g" "a-c" "b-g" "a-d" "a-g" "a-c" "a"
^
refers to start of the string, $
as end of the string.
Upvotes: 1