Read column names as numbers when importing a data file to R
When you read in a data file from CSV or some other text format, R will examine the column headings and ensure that they are in correct “R-format”. If your headings are all numbers, for example years, then R will convert them to character strings and prepend “X” to each heading.
You can overcome this behaviour and force R to read the headings as they come. Your headings are still converted to character strings but these are easier to coerce to a numeric value.
Use check.names = FALSE
Look at these data (you can view/get the datafile here):
Spp 1996 1997 1998 1999 2000 M.bro 88 47 13 33 86 Or.tip 90 14 36 24 47 Paint.l 50 0 0 0 4 Pea 48 110 85 54 65 Red.ad 6 3 8 10 15 Ring 190 80 96 179 145
The first column contains species names and the rest are numbers. The column names are mostly years (the sampling year). If you read these data into R the column names will be prepended with “X”, which is not helpful.
If you add check.names = FALSE as a parameter to read.xxxx() you’ll force R to accept the names of the columns as they are.
> bfy <- read.table(file.choose(), header = TRUE, sep = "\t", check.names = FALSE, row.names = 1) > bfy 1996 1997 1998 1999 2000 M.bro 88 47 13 33 86 Or.tip 90 14 36 24 47 Paint.l 50 0 0 0 4 Pea 48 110 85 54 65 Red.ad 6 3 8 10 15 Ring 190 80 96 179 145 > as.numeric(colnames(bfy)) [1] 1996 1997 1998 1999 2000
The data object will contain column names that are character but it is easy to coerce them to numeric with the as.numeric() command.
Of course this is a bit of a cheat… the column names are not real numbers. You cannot make the column names “properly” numeric but in this (character) form you can easily coerce them to be numeric when you need with the as.numeric() command.
Comments are closed.