Home > database >  Keep first and last element from a character vector in R
Keep first and last element from a character vector in R

Time:01-29

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.

CodePudding user response:

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.

  •  Tags:  
  • Related