Farhan
Farhan

Reputation: 77

Keep first and last element from a character vector in R

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

Answers (1)

Ronak Shah
Ronak Shah

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

Related Questions