Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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
.,.,.,.
like image 314
user3292488 Avatar asked Feb 10 '14 11:02

user3292488


1 Answers

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

or

df$filname <- substr(df$filname, 0, 3)
like image 185
lukeA Avatar answered Nov 16 '22 00:11

lukeA