R: Only keep the 3 (x) first characters in a all rows in a column?

r

Solution

df$filname <- sub("^(\\d{3}).*$", "\\1", df$filname)

or

df$filname <- substr(df$filname, 0, 3)

Problem

I have imported a few thousand xls files into a data.frame and I added a column with the filename. Thus I have the data ``` data1 data2 data3 filname A A2 A3 301fg.xls B B2 B3 302gfg.xls C C2 C3 303gfsddf.xls .,.,.,. ``` I want to renamne the names in the filename column to only contain the 3 first characters/digits thus giving: ``` data1 data2 data3 filname A A2 A3 301 B B2 B3 302 C C2 C3 303 .,.,.,. ```

Original source