Search code examples
rstringcharacter-encodinggsubstrsplit

R: How to shorten data frame values to first character


I would like to shorten the values of one column of my data.frame. Right now, each value consists of many letters, such as

df$col1
[1] AHG    ALK    OPH   BCZ   LKH    QRQ    AAA   VYY

what I need is only the first letter:

df$col1
[1] A    A    O   B   L    Q    A   V

I have read other entries that suggested to use gsub, stri_replace_all_charclass, or strsplit. But I am afraid I need help to implement this.


Solution

  • You can use strtrim

    df$col1 <- strtrim(df$col1, 1)